Leetcode:same Tree-Determine if two trees are equal

Source: Internet
Author: User

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

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.