Judgment of the same binary tree

topic

Judgment of the same binary tree

Topic requirements

insert image description here
topic link

example

answer

method one,

recursion

Implementation ideas

If two trees are visited together from the root node, return false if one node is not equal, and return true if both nodes are equal.

Time Complexity and Space Complexity

Time complexity: O(N)
Space complexity: O(N)

the code

bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    
    
    //如果两个结点都为空,则相等,返回true
    if(p==NULL&&q==NULL)
    {
    
    
        return true;
    }
    //如果有一个结点为空,另一个不为空,则两个结点不相等,即两棵二叉树不相等,
    if(p==NULL||q==NULL)
    {
    
    
        return false;
    }
    //如果两个结点的值不相等,则两个结点不相等,即两棵二叉树不相等
    if(p->val!=q->val)
    {
    
    
        return false;
    }
    //如果p和q两个结点相等,就判断p结点的左子树和q结点的左子树是否相等,判断p结点的右子树和q结点的右子树是否相等,如果都相等就返回true,如果有一组结点不相等就返回false
    return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}

Method Two,

Implementation ideas

Time Complexity and Space Complexity

the code


Guess you like

Origin blog.csdn.net/dong132697/article/details/132585134
Recommended