剑指offer之 对称的二叉树

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路

  1. 首先判断根节点左右子树是否都存在或都为NULL,若不满足则false,若满足则进一步将树分为两棵树,根据Is_Same判断两棵树是否对称。
  2. 非递归,使用栈来压入左右两颗子树,若相同则同进同出,若不同则返回false

代码

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;
    }
};

方法二:

链接: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;
    }
发布了85 篇原创文章 · 获赞 0 · 访问量 399

猜你喜欢

转载自blog.csdn.net/weixin_38312163/article/details/104810528