摘要: 碰到二叉树的问题,差不多就是深搜、广搜,递归那方面想想了,当然如果要考虑一下空间、时间,还需要进行剪枝和压缩处理。这题比较简单:判断两个树是否相等,可以递归的判断子树是否相等,最后找到边界条件就是是否都为空,都不为空时节点里面的值是否相等。
一、递归
题目描述
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
思路- 碰到二叉树的问题,差不多就是深搜、广搜,递归那方面想想了,当然如果要考虑一下空间、时间,还需要进行剪枝和压缩处理。这题比较简单:判断两个树是否相等,可以递归的判断子树是否相等,最后找到边界条件就是是否都为空,都不为空时节点里面的值是否相等。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null){
return true;
}
else if(p==null||q==null){
return false;
}
else if(q.val!=p.val){
return false;
}
else{
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
}
}
二、动态规划
题目描述
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens ="leetcode",dict =["leet", "code"]. Return true because"leetcode"can be segmented as"leet code".
思路- dp的题目,写了几道了。核心无非就是确定dp数组和状态转移方程。这几道题都有明显的特点,那就是dp数组记录的就是所求的答案,所以答案一般都是dp[s.length()]这种形式的。
- 有了上面的总结,再来看着道题目。要求一串字母是否可以由所给的字典中的单词拼出来,要求返回布尔型。那好,也同时提示我们了dp数组就是记录它的子串是否能满足要求,类型是布尔型:dp[i]表示的是s[0,i-1]这个子串能否满足要求。
- dp[i]=dp[j]&&s[j,i]是否在字典中(0=0;i--){ if(dict.contains(s.substring(i,index))){ dfs(s,i,dict,s.substring(i,index)+" "+temp); } } } }
原文链接
本文为云栖社区原创内容,未经允许不得转载。