您的位置:首页 > 其它

Same Tree problem on leetcode

2014-11-25 21:42 267 查看

Problem Description:


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.

Tags: Tree, Depth-first Search

Class: Easy


Source Code:

we can solve this problem using just one line code, like this:

public boolean isSameTree(TreeNode p, TreeNode q) {
return p == null || q == null ? p == null && q == null : p.val != q.val ? false : isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

Although the solution is clean, However, it is difficult to read. Don't worry, we can rewrite it to a more understandable form, like this:

public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return p == null && q == null;
else if (p.val == q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
else return false;
}

cnblogs did a bad job on support for Markdown, you can find a more beautiful composing here
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: