LeetCode101—Symmetric Tree

LeetCode101—Symmetric Tree

原题

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

判断一棵树是否“对称”

分析

这种树的结构实在太特殊了,就把第一个示例的先序、中序、后序遍历的结果都写了出来,并没有发现什么规律,但是仔细一想,既然是对称的,那么左右子树是可以互换的,也就是说递归的时候也可以互换:以先序遍历来说,访问根->递归访问左子树->递归访问右子树;互换其左右子树也就是:访问根->递归访问右子树->递归访问左子树。两种情况的结果一致。当然可能有更方便的办法,等哪天学习了再补充。

代码

class Solution {
private:
    void dfs(TreeNode* root,vector<int >&result)//先序遍历(根->左子树->右子树)
    {
        if (root == NULL)
        {
            result.push_back(-1);
            return;
        }
        result.push_back(root->val);
        dfs(root->left, result);
        dfs(root->right, result);
    }
    void dfsr(TreeNode* root, vector<int >&result)//先序遍历(根->右子树->左子树)
    {
        if (root == NULL)
        {
            result.push_back(-1);
            return;
        }
        result.push_back(root->val);
        dfsr(root->right, result);
        dfsr(root->left, result);
    }
public:
    bool isSymmetric(TreeNode* root) {
        vector<int>res1;
        vector<int>res2;
        dfs(root, res1);
        dfsr(root, res2);
        return equal(res1.cbegin(), res1.cend(), res2.cbegin());
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值