LeetCode | 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 false;
        if (q==null && p!=null) return false;
        if (p==null && q==null) return true;
        if (p.val != q.val) return false;   //一定要把为null的情况都考虑过了,才能用p.val,否则可能出现空指针异常
        
        boolean leftresult = isSameTree(p.left,q.left);
        boolean rightresult = isSameTree(p.right,q.right);
        
        return leftresult && rightresult;
    }
}



 

posted @ 2014-10-27 09:21  Mr.do  阅读(116)  评论(0编辑  收藏  举报