100. 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 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了一下發(fā)現(xiàn)可以用遞歸的思路來做。具體思路是:如果p樹的當前節(jié)點的val與q樹中當前節(jié)點的val相等,且p樹中當前子樹的左、右子樹和q樹中當前子樹的左、右子樹相同,則p、q樹中,以當前節(jié)點為跟節(jié)點的兩棵樹相同。

代碼如下:

/**
 * 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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容