leetcode 101. Symmetric Tree

题目描述

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

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

解题思路:

常规的二叉树问题,递归的解法:

/**
 * 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 == 0)
            return true;
        return isMirror(root -> left, root -> right);
    }
private:
    bool isMirror(TreeNode* t1, TreeNode* t2){
        if(t1 == 0 && t2 == 0)
            return true;
        if(t1 == 0 || t2 == 0)
            return false;
        if(t1 -> val != t2 -> val)
            return false;
        return isMirror(t1 -> left, t2 -> right) && isMirror(t1 -> right, t2 -> left);
    }
};

由于每个顶点都需要遍历一遍,所以这个算法的时间复杂度为O(n),了leetcode上运行时间为4ms,由于用到了递归,所以空间复杂度为树的高度,在最差的情况下,树高为n,因此最差情况下空间复杂度为O(n)。


非递归解法:

/**
 * 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 == 0)
            return true;
        stack<treePair> s;
        s.push(treePair(root -> left, root -> right));
        while(!s.empty()){
            treePair tmp;
            tmp = s.top();
            s.pop();
            TreeNode *t1, *t2;
            t1 = tmp.t1, t2 = tmp.t2;
            if(t1 == 0 && t2 == 0)
                continue;
            if(t1 == 0 || t2 == 0)
                return false;
            if(t1 -> val != t2 -> val)
                return false;
            s.push(treePair(t1 -> left, t2 -> right));
            s.push(treePair(t1 -> right, t2 -> left));
        }
        return true;
    }
private:
    struct treePair{
        TreeNode *t1, *t2;  
        treePair(TreeNode* x = 0, TreeNode* y = 0):t1(x), t2(y){}
    };
};
时空复杂度与上面的递归方法是一致的,运行时间也是4ms。
在leetcode上有篇 题解,里面也提供了两种方法,但是,里面采用了isMirror(root, root),这个函数,结果虽然没有错,代码也简洁了,但是实际上这是将原来的树作为一棵新树的左右节点,所以后面的比较也会翻倍,但在时间复杂度而言来说是一样的(N和2N是一致的),而这会导致很多没必要的计算,还不如多写个判断,程序也容易理解。

以上纯属个人理解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值