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

leetcode 101. Symmetric Tree

时间:2017-04-26 14:39:37      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:amp   solution   images   seq   .com   init   treenode   tree node   pre   

技术分享

//递归的解法

/**
 * 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;
        TreeNode *pleft = root->left;
        TreeNode *pright = root->right;
        return isequal(pleft,pright);    
    }
    
    bool isequal(TreeNode *pleft, TreeNode *pright){
        if(pleft == NULL && pright == NULL )
            return true;
        if(pleft == NULL && pright != NULL)
            return false;
        if(pleft != NULL && pright == NULL)
            return false;
        if(pleft->val == pright->val)
            return isequal(pleft->left,pright->right) && isequal(pleft->right,pright->left);
        else{
            return false;
        }
    }
};

  //循环的方法    很悲哀 不太会用C++ STL模板中的stack 和pair   所以用了python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root is None:
            return True
        
        stack = [[root.left,root.right]]
        
        while len(stack) > 0:
            pair = stack.pop()
            pleft = pair[0]
            pright = pair[1]
            
            if pleft is None and pright is None:
                continue
            if pleft is None or pright is None:
                return False
            if pleft.val == pright.val:
                stack.append([pleft.left,pright.right])
                stack.append([pleft.right,pright.left])
            else:
                return False
    
        return True

 

leetcode 101. Symmetric Tree

标签:amp   solution   images   seq   .com   init   treenode   tree node   pre   

原文地址:http://www.cnblogs.com/strongYaYa/p/6768138.html

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