[LeetCode-interview algorithm classic-Java implementation] [100-Same Tree (whether the two sides are the Same)], leetcode -- java

Source: Internet
Author: User

[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.

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.