leetcode 101. Symmetric Tree

//递归的解法

/**
 * 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
原文地址:https://www.cnblogs.com/strongYaYa/p/6768138.html