title : 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.
problem-Solving ideas : The basic meaning of this question is to determine whether two binary trees are the same, because the recursive thinking is not very skilled, so the beginning of a non-recursive method of writing, but the old one case can not pass. Later, with a recursive thinking, I finally passed all the test cases. Before each encounter recursive problems will be a little resistance, worry about a bit of bugs, usually practice very little, the following is a simple summary of the idea of recursion:
The program itself calls its own programming skills called recursion , there are four characteristics of recursion:
1. There must be a termination condition that can eventually be reached, otherwise the program will fall into an infinite cycle;
2. Sub-problems are smaller than the original problem on the scale, or closer to the termination conditions;
3. Sub-problem can be solved by recursive call again or by satisfying termination condition.
4. The solution of sub-problems should be combined into the solution of the whole problem.
The above problem is a typical recursive problem, first of all to determine whether two binary root node is the same, and then determine whether the child node is the same or not. The code is as follows:
/* Determine if two binary trees are the same */class TreeNode { int val; TreeNode left; TreeNode right; TreeNode (int x) {val = x;}} public class Solution {public Boolean issamenode (TreeNode a,treenode B)//Determine if two nodes are the same {if (a==null&&b==null) //Both are empty nodes, the same return true;else if (a!=null&&b!=null&&a.val==b.val)//Are not empty nodes and the node values are equal, the same return true; else//the rest of the conditions are not the same return false;} public boolean issametree (TreeNode p, TreeNode q) { if (p==null&&q==null) return true;if (! Issamenode (P, q)) return false;if (Issamenode (P, Q)) return Issametree (P.left, Q.left) &&issametree ( P.right, q.right); return false; }}
"Leetcode OJ" Same Tree