Offer to prove safety of symmetrical binary tree

Title Description

Please implement a function, a binary tree is used to determine not symmetrical. Note that if a binary image is a binary tree with this same definition as symmetrical.

Thinking

  1. The root node first determines whether the left and right subtrees are present or are NULL, it is not satisfied false, it is further satisfied if the tree is divided into two trees, according Is_Same determines whether two trees symmetrical.
  2. Non-recursive use of the stack to press the left and right two subtrees, if the same is into the same, if false if different

Code

class Solution {
public:
    vector<int> left;
    vector<int> right;
    bool isSymmetrical(TreeNode* pRoot)
    {
        if(pRoot == NULL) return true;
        if(pRoot->left != NULL && pRoot->right != NULL)
            return Is_same(pRoot->left,pRoot->right);
        else if(pRoot->left == NULL && pRoot->right == NULL)
            return true;
        return false;
    }
    bool Is_same(TreeNode* pLeft,TreeNode* pRight)
    {
        if(pLeft == NULL && pRight == NULL)
            return true;
        if(pLeft!=NULL && pRight!=NULL)
        {
            if(pLeft->val == pRight->val)
            {
                if(Is_same(pLeft->left,pRight->right)&&Is_same(pLeft->right,pRight->left))
                    return true;
            }
        }
        return false;
    }
};

Method Two:

链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion
来源:牛客网

boolean isSymmetricalDFS(TreeNode pRoot)
    {
        if(pRoot == null) return true;
        Stack<TreeNode> s = new Stack<>();
        s.push(pRoot.left);
        s.push(pRoot.right);
        while(!s.empty()) {
            TreeNode right = s.pop();//成对取出
            TreeNode left = s.pop();
            if(left == null && right == null) continue;
            if(left == null || right == null) return false;
            if(left.val != right.val) return false;
            //成对插入
            s.push(left.left);
            s.push(right.right);
            s.push(left.right);
            s.push(right.left);
        }
        return true;
    }
Published 85 original articles · won praise 0 · Views 399

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/104810528