The problem:
Given binary trees, write a function to check if they is equal or not.
The binary trees is considered equal if they is structurally identical and the nodes has the same value.
My Analysis:
This problem are very easy, and we can conclude some common routines in writing a recursion program.
1. Usually, we need information (information from post recursion level) to make decision
Return helper (Cur_root1.left, Cur_root2.left) && Helper (cur_root1.right, cur_root2.right);
Thus, until we reach the base case, we won ' t return "true" value.
if NULL NULL // Also take care of the illegal base case!!! return true;
2. During the recursion level, which is not a he base level, we won ' t return "true" value based on current level ' s judgement. But we can return ' false ' value to indicate the violation happens at the current level, we no longer need to go on the sea rching!
Note:this idea was very classic in constraining the searching space.
if (Cur_root1.val! = cur_root2.val ) return false;
My Solution:
Public classSolution { Public BooleanIssametree (TreeNode p, TreeNode q) {returnHelper (P, q); } Private BooleanHelper (TreeNode cur_root1, TreeNode cur_root2) {if(Cur_root1 = =NULL&& Cur_root2 = =NULL)//both roots is null, only base case or violation can directly return return true; if(Cur_root1 = =NULL|| Cur_root2 = =NULL)//Only one root is null return false; if(Cur_root1.val! =cur_root2.val)return false; returnHelper (Cur_root1.left, Cur_root2.left) &&Helper (cur_root1.right, cur_root2.right); }}
[LEETCODE#100] Same Tree