[LeetCode-interview algorithm classic-Java implementation] [100-Same Tree (whether the two sides are the Same)], leetcode -- java
[100-Same Tree (whether the two trees are the Same )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Theme
Given two binary trees, determine whether the two trees are equal.
Only when the two shards have the same structure and the node values are equal will they be equal.
Solutions
Use recursion to solve the problem. First, judge whether the current node value is equal. If the values are equal, compare the Left and Right Subtrees. Only when all the nodes are equal can they be equal.
Code Implementation
Tree node class
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm Implementation class
public class Solution { public boolean isSameTree(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; } return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47333329]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.