"100-same tree (two trees are the same)""leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"Original Question
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.
Main Topic
Given two binary trees, determine whether the two trees are equal.
Only if the two trees have the same structure, the node values will be equal when they are equal.
Thinking of solving problems
Using recursion to solve, first determine whether the current node value is equal, if the equality is then compared to the left and right sub-tree, only if all the nodes are equal to equal.
Code Implementation
Tree Node class
publicclass TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm implementation class
Public classSolution { PublicBooleanIssametree(TreeNode p, TreeNode q) {if(p = =NULL&& Q = =NULL) {return true; }if(P! =NULL&& Q = =NULL) {return false; }if(p = =NULL&& Q! =NULL) {return false; }returnP.val = = Q.val && issametree (p.left, Q.left) && issametree (P.right, q.right); }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special InstructionsWelcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47333329"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "100-same tree (whether two trees are the same)"