zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    ASP.NET操作文件大全
    Jquery1.7中文文档提供下载了
    修改server2005数据库的区分大小写设置
    SQL SERVER 设置自动备份和删除旧的数据库文件
    ASP.NET关闭下载窗口
    DB2通用分页存储过程
    ASP.NET生成压缩文件(rar打包)
    上传文件实体类
    【Demo 0104】注册/注销热键
    【Demo 0018】SEH结束处理程序
  • 原文地址:https://www.cnblogs.com/strongYaYa/p/6768138.html
Copyright © 2011-2022 走看看