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