Symmetric Tree leetcode

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

看到这个题首先想到的是中序遍历,遍历结果是否是前后相同,也就是是否是“回文”,我使用了一个栈,遍历到root之前是push,遍历到root之后查看是否相同。
中序遍历使用了非递归方法,代码写好后,运行测试发现有逻辑漏洞,如[1,2,3,3,#,2,#]这个树的中序遍历就是3,2,1,2,3也是回文,看来仅仅中序遍历是无法判断镜像树的。该思路错误

查看了下网上其它人的答案
发现可以使用队列或栈来实现
思路就是两两比较,左子树与右子树比较,左子树的左子树与右子树的右子树比较,左子树的右子树与右子树的左子树比较
bool isSymmetric(TreeNode* root) {
    if (!root) return true;
    queue<TreeNode*> check;

    check.push(root->left);
    check.push(root->right);

    while (!check.empty()) {
        TreeNode* node1 = check.front();
        check.pop();
        TreeNode* node2 = check.front();
        check.pop();
        if (!node1 && node2) return false;
        if (!node2 && node1) return false;
        if (node1 && node2) {
            if (node1->val != node2->val) return false;
            check.push(node1->left);
            check.push(node2->right);
            check.push(node1->right);
            check.push(node2->left);
        }
    }

    return true;
}

 

 

转载于:https://www.cnblogs.com/sdlwlxf/p/5140510.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值