码迷,mamicode.com
首页 > 其他好文 > 详细

101. Symmetric Tree

时间:2016-08-21 00:45:20      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

1. 问题描述

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.
Tags: Tree Depth-first Search Breadth-first Search

2. 解题思路
3. 代码

class Solution {
public:
    bool isSymmetric(TreeNode* root) 
    {
        if (!root)
        {
            return true;
        }
        if (NULL != root->left && NULL != root->right)
        {
            return isSymme(root->left, root->right);
        }
        else if (NULL == root->left && NULL == root->right)
        {
            return true;
        }
        else
        {
            return false;    
        }
    }
private:
    bool isSymme(TreeNode* lh, TreeNode* rh)
    {
        if (NULL == lh && NULL == rh)
        {
            return true;
        }
        else if (NULL != lh && NULL != rh)
        {
            if (lh->val != rh->val)
            {
                return false;
            }
            else
            {
                return isSymme(lh->left, rh->right) && isSymme(lh->right, rh->left);
            }
        }
        else
        {
            return false;
        }        
    }
};

4. 反思

101. Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/whl2012/p/5791579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!