【Symmetric Tree】cpp

本文探讨如何使用递归和迭代方法判断二叉树是否对称,涉及二叉树数据结构、栈操作及同题转换策略。

题目:

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

 

Note:
Bonus points if you could solve it both recursively and iteratively.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
            if (!root) return true;
            stack<TreeNode *> staL, staR;
            staL.push(root->left);
            staR.push(root->right);
            while ( !staL.empty() && !staR.empty() )
            {
                TreeNode *tmpL = staL.top();
                staL.pop();
                TreeNode *tmpR = staR.top();
                staR.pop();
                if ( !tmpL && !tmpR ) continue;
                if ( !tmpL || !tmpR ) return false;
                if ( tmpL->val != tmpR->val ) return false;
                staL.push(tmpL->right);
                staL.push(tmpL->left);
                staR.push(tmpR->left);
                staR.push(tmpR->right);
            }
            return staL.empty() && staR.empty();
    }
};

tips:

深搜思想。设立两个栈:左栈和右栈。

从根节点开始:左子树用左栈遍历(node->left->right);右子树用右栈遍历(node->right->left)。

这样就可以转化为Same Tree这道题了(http://www.cnblogs.com/xbf9xbf/p/4505032.html

转载于:https://www.cnblogs.com/xbf9xbf/p/4505116.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值