equivalent binary tree
Check that two binary trees are equivalent. Equivalence means that first two binary trees must have the same structure, and the number of nodes on each corresponding position is equal.
Sample Example
1 1 / \ / 2 2 and 2 2 / /4 4
is two equivalent two-fork tree.
1 1 / \ / 2 3 and 2 3 / 4 4
is not equivalent.
Solving
The tree has the same structure and the node values are equal.
Direct recursion
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramA, B, the root of the binary trees. * @returntrue if they is identical, or false. */ Public Booleanisidentical (TreeNode A, TreeNode b) {//Write Your code here if(A = =NULL&& b = =NULL){ return true; } if(A = =NULL&& B! =NULL|| a!=NULL&& b = =NULL|| A.val! =b.val) { return false; } returnIsidentical (A.left, B.left) &&isidentical (A.right, b.right); }}
Lintcode: Equivalent binary tree