现在的位置: 首页 > 综合 > 正文

LeetCode OJ –问题与解答 Same Tree

2014年04月05日 ⁄ 综合 ⁄ 共 480字 ⁄ 字号 评论关闭
题目


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.

判断两棵树是否相等。


思路


1 一样是递归的思路

2 关键是考虑到叶节点,null节点的不同情况。 如果都是null,返回true。如果有一个null ,则返回false。剩下的就是都非null的情况,继续递归。

3 这种题目必须一次做对。


代码


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;
        }
        
        return p.val==q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}

抱歉!评论已关闭.