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 a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public boolean isSameTree(TreeNode p, TreeNode q)
{
}
}
Solution:
一開始我的想法是,分別求兩棵樹的前序和中序遍歷,然后兩兩對比。如果完全一致則可判定這兩棵樹是相同的。(感覺有點繁瑣,有待驗證可行性)
后來Google了一下發現可以用遞歸的思路來做。具體思路是:如果p樹的當前節點的val與q樹中當前節點的val相等,且p樹中當前子樹的左、右子樹和q樹中當前子樹的左、右子樹相同,則p、q樹中,以當前節點為跟節點的兩棵樹相同。
代碼如下:
/**
* Definition for a binary tree node.
* 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) || (p != null && q == null))
return false;
else // in this case, both p and q are not null
{
// so we compare their value
if(p.val != q.val)
return false;
else // p.val == q. val, so we move forawrd to their children
{
boolean leftChildResult, rightChildResult;
leftChildResult = isSameTree(p.left, q.left);
rightChildResult = isSameTree(p.right, q.right);
return leftChildResult & rightChildResult; // only when both of their left and right subtree are same, this two trees are same.
}
}
}
}
參考:
http://blog.csdn.net/u200814499/article/details/40076041