1. Title
Same tree (judging whether two trees are equal)
2. Address of the topic
https://leetcode.com/problems/same-tree/
3. Topic content
English: 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.
Chinese: Given two binary trees, write a function to determine whether the two trees are equal. If the structure of the two trees is equal to the values held in each node, the two trees are considered equal.
4. Methods of Solving problems
In this paper, we can use the method of first root traversal to investigate each node recursively from top to bottom. In the case of any pair of nodes, if the left and right branches are empty and the Val values in the nodes are not equal, the two trees are considered not the same tree, otherwise they will continue to be inspected. If the two trees are not the same tree after the end of the traversal, the two trees are equal.
The Java code to solve the problem is as follows:
/** * function Description:leetcode 100 - same tree * developer:tsybius2014 * Development Date: August 12, 2015 */public class solution { / ** * determine if two trees are equal * @param p tree P * @param q Tree q * @return */ public boolean issametree (TreeNode p, TREENODE Q) { if (p == null & & q == null) { return true; } else if ( (p == null && q != null) | | (p != null && q == null) | | p.val != q.val | | !issametree (P.left, q.left) | | !issametree (p.right, q.right)) { return false; } else { return true; } }}
END
Leetcode:same Tree-Determine if two trees are equal