100. Same Tree

//本文內容來自StarSight,歡迎訪問。


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) {
        boolean l=false,r=false;
        if(p==null){
            if(q==null)
                return true;
            else if(q!=null)
                return false;
        }
        
        if(q==null){
            return false;
        }
           
            
        if(p.left!=null)
            l = isSameTree(p.left,q.left);
        else if(q.left==null)
            l = true;
        
        if(p.right!=null)
            r = isSameTree(p.right,q.right);
        else if(q.right==null)
            r = true;
            
        if(p.val==q.val&&l==true&&r==true)
            return true;
            
        return false;
    }
}


依次遍歷,沒啥好說的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章