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

[LeetCode] Symmetric Tree

时间:2015-05-17 18:48:13      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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

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

解题思路:

题目要求分别用递归法和迭代法做。

1、递归法。思路挺简单,每次检查一对节点,验证这对节点的值是否相同,并且节点1的左孩子与节点2的右孩子的对称的,并且节点1的右孩子与节点2的左孩子是对称的。否则,返回false。

/**
 * 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) {
        return isSysmetricHelp(root, root);
    }
    
    bool isSysmetricHelp(TreeNode* root1, TreeNode* root2){
        if(root1==NULL && root2==NULL){
            return true;
        }
        if(root1==NULL || root2==NULL){
            return false;
        }
        if(root1->val != root2->val){
            return false;
        }
        return isSysmetricHelp(root1->left, root2->right)&&isSysmetricHelp(root1->right, root2->left);
    }
};
2、迭代法。有句话,递归转化成非递归,无非就是用栈或堆来存储中间状态。我们用两个队列来存储待比较的两个节点即可。

/**
 * 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==NULL){
            return true;
        }
        //两个队列的大小逻辑上一定相同
        queue<TreeNode*> left({root});
        queue<TreeNode*> right({root});
        while(!left.empty()){
            TreeNode* leftNode = left.front();
            TreeNode* rightNode = right.front();
            left.pop();
            right.pop();
            if(leftNode->val!=rightNode->val){
                return false;
            }
            if(leftNode->left!=NULL&&rightNode->right!=NULL){
                left.push(leftNode->left);
                right.push(rightNode->right);
            }else if(leftNode->left!=NULL || rightNode->right!=NULL){
                return false;
            }
            if(leftNode->right!=NULL&&rightNode->left!=NULL){
                left.push(rightNode->left);
                right.push(leftNode->right);
            }else if(leftNode->right!=NULL || rightNode->left!=NULL){
                return false;
            }
        }
        
        return true;
    }
};


[LeetCode] Symmetric Tree

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45789951

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