[C + +] leetcode:89 same Tree

Source: Internet
Author: User

Title:

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.

Answer 1:dfs Recursive method

idea: first determine whether the root node is equal, and then recursively Judge Saozi right subtree.

Attention:

1. Be careful to judge special cases, if both trees are empty trees, return true. Returns False if there is only one empty number and the other is not empty. You can only judge the value or push of a non-empty payment.

if (p = = NULL | | q = NULL) return p = = q;

Complexity: O (n), n is the number of nodes in the tree.

AC Code:

/** * Definition for binary tree * struct TreeNode {*     int val; *     TreeNode *left; *     TreeNode *right; *     Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:    bool Issametree (TreeNode *p, TreeNode *q) {        if (p = = NULL && q = = null)        {
   
    return true;        }        else if (P! = NULL && Q! = null)        {            return (P->val = = q->val) && issametree (P->left, Q-&G T;left) && Issametree (P->right, q->right);         }        else            return false;    }};
   

Answer 2: Non-recursive method

idea: sequence traversal tree, we build two queues to hold the tree's sequence nodes. Each time an element is fetched from the queue, if their value is equal, they continue to traverse its child nodes. In determining whether the sub-nodes of the two trees are equal, only two cases are equal, either the nodes are not empty at the same time and the values are equal or null at the same time. If one is empty and the other is non-empty, the two trees are different.

Attention:

1. To ensure that the structure of the tree is the same, must be stored in the sub-nodes before the location of the node is determined to be consistent.

                Need to check if the left and right children of the node are in, if inconsistent (one without child nodes, one with a child node), stating unequal                if (tmpp->left && tmpq->left)                {                    Treep.push (tmpp->left);                    Treeq.push (Tmpq->left);                }                else if (Tmpp->left | | tmpq->left)                    return false;

The binary tree is stored in the form

  1  /  2   3    /   4         5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

#代表一条路径的终点, which means there are no nodes here, is used only for placeholders (characterizing binary tree structures) and does not represent a node . When dealing with tree problems, follow the tree structure to think about the problem. No need to consider the impact of #. if (root->left) indicates whether the root node has left nodes, there is ture, no false. does not change to true because it is stored as # here.

2. We can only put non-empty nodes into the queue, so we need to first determine whether the node is not empty.

if (p) Treep.push (p), if (q) treeq.push (q);
3. If the last queue is empty and the other queue is not empty, then the tree is not equal, so be careful to make a final judgment.
if (Treep.empty () && treeq.empty ())            return true;        else            return false;
AC Code:

/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {Public:bool issametree (TreeNode *p, TreeNode *q) {///Two the node that does not exist in the tree is saved as # (vacated position) Tmpp->left = #.                Until the last leaf node, then no storage, Tmpp->left will become empty if (P = = NULL | | q = = NULL) return p = = q;        Queue<treenode*> Treep;        Queue<treenode*> Treeq;        if (p) Treep.push (p);                if (q) treeq.push (q); while (! Treep.empty () &&!            Treeq.empty ()) {treenode* tmpp = Treep.front ();            Treep.pop ();            treenode* TMPQ = Treeq.front ();                        Treeq.pop ();                if (Tmpp->val = = Tmpq->val) {//need to check if the left and right children of the node are in, if inconsistent (one has no child nodes, one has a child node), indicating unequal                   if (tmpp->left && tmpq->left) {Treep.push (tmpp->left); Treeq.push (Tmpq->left);                                } else if (Tmpp->left | | tmpq->left) return FALSE;                    if (tmpp->right && tmpq->right) {Treep.push (tmpp->right);                Treeq.push (Tmpq->right);            } else if (Tmpp->right | | tmpq->right) return FALSE;        } else return false;        } if (Treep.empty () && treeq.empty ()) return true;    else return false; }};



[C + +] leetcode:89 same Tree

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.