"Leetcode-Interview algorithm classic-java implementation" "100-same tree (whether two trees are the same)"

Source: Internet
Author: User

"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)"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.