https://oj.leetcode.com/problems/same-tree/
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; if(p != null && q != null && p.val == q.val){ return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }else{ return false;
} } }
解题思路:
递归。两个树相等,当且仅当当前节点value相等,并且左右两个子树也都相等。
退出条件:
当前节点为空。
注意点:
搞清楚当前阶段null和left或right为null的区别。
或者下面的代码更清楚一点
/** * 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(p != null && q == null){ return false; }else if(p.val != q.val){ return false; }else{ //if(p.val == q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } } }
还有一种解法,不是很straight forward,但是给了另一种思路。
和 Anagrams 的题目类似,我们考虑给same tree一样的一种code,或者叫签名,不同的tree不同的code。这样对两棵树进行操作后,比较他们的code就可以了。这实际上是一种serializatin的思路——将二叉树序列化表示。
这里直接讲出结论,只有preorder和level order的traversal是可以序列化二叉树的,inorder和postorder不可以,得出的code无法回头生成原来的二叉树。思考一下,为什么?代码直接给出,如下。
/** * 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) { StringBuffer result_p = new StringBuffer(); StringBuffer result_q = new StringBuffer(); preOrder(p, result_p); preOrder(q, result_q); return result_p.toString().equals(result_q.toString()); } public void preOrder(TreeNode root, StringBuffer result){ if(root == null){ result.append("#"); return; } result.append(root.val); preOrder(root.left, result); preOrder(root.right, result); } }