双指针:可以指向一颗树(左右节点),也可以指向两棵树(根结点)
判断两棵树是否相同
思路:使用递归处理
条件为:1.两个为空,2.一个为空,一个不为空 3.值不相同
如果以上条件都不满足,则继续比较相关的子节点(左右孩子)
public boolean isSameTree(TreeNode p, TreeNode q) { //如果都为空我们就认为他是相同的 if (p == null && q == null) return true; //如果一个为空,一个不为空,很明显不可能是相同的树,直接返回false即可 if (p == null || q == null) return false; //如果对应位置的两个结点的值不相等,自然也不是同一个棵树 if (p.val != q.val) return false; //走到这一步说明节点p和q是完全相同的,接下来需要再判断其左左和右右是否满足要求了 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }
对称二叉树
就是一个树的内测与外侧相同(左对右,右对左)
条件:1.两个为空,2.一个为空,一个不为空 3.值不相同
否则就递归判断 孩子结点(左对右,右对左)结点
class Solution { //主方法 public boolean isSymmetric(TreeNode root) { if(root==null){ return true; } return check(root.left, root.right); } public boolean check(TreeNode p,TreeNode q){ if (p == null && q == null) { return true; } if (p == null || q == null) { return false; } if( p.val != q.val){ return false; } return check(p.left, q.right) && check(p.right, q.left); } }
合并二叉树
条件:有则创,无则原
为空则返回另一个,都不为空则创建一个新的结点,孩子结点不断的遍历之前结点
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null) { return t2; } if (t2 == null) { return t1; } TreeNode merged = new TreeNode(t1.val + t2.val); merged.left = mergeTrees(t1.left, t2.left); merged.right = mergeTrees(t1.right, t2.right); return merged; }
路径专题
二叉树的所有路径
直接用递归,找到没有孩子结点为止
public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); dfs(root, "", res); return res; } void dfs(TreeNode root, String path, List<String> res) { if (root == null) return; if (root.left == null && root.right == null) { //别遗忘了还有最后这个元素 res.add(path + root.val); return; } dfs(root.left, path + root.val + "->", res); dfs(root.right, path + root.val + "->", res); }
路径总和
可以根据上一道题获得总其路径,让路径上的值相加,或则直接将总的值不断向减,减到最后面相等。
相加
public boolean hasPathSum(TreeNode root, int targetSum) { int s=0; return hasPathSum(root, targetSum,s); } public static boolean hasPathSum(TreeNode root, int sum,int s) { if (root == null) { return false; } if (root.left == null && root.right == null) { if (s==sum-root.val){ return true; }else { return false; } } return hasPathSum(root.left, sum ,s+root.val) || hasPathSum(root.right, sum,s+root.val); }
直接减
public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null) { return sum == root.val; } boolean left= hasPathSum(root.left, sum - root.val) ; boolean right=hasPathSum(root.right, sum - root.val); return left|| right; }
翻转的妙用
直接一层一层的翻转
public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode temp=root.left; root.left=root.right; root.right=temp; invertTree(root.left); invertTree(root.right); return root; }
public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } invertTree(root.left); invertTree(root.right); TreeNode temp=root.left; root.left=root.right; root.right=temp; return root; }