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
  • 相关阅读:
    [Sdoi2016]征途
    何时会发生db file sequential read等待事件?
    oracle分布式事务总结
    db file scattered read 等待事件
    db file sequential read (数据文件顺序读取)
    INDEX_JOIN
    Oracle优化器介绍
    GC Buffer Busy Waits处理(转载)
    Oracle V$SESSION详解
    Oracle锁表(转载)
  • 原文地址:https://www.cnblogs.com/strongYaYa/p/6768138.html
Copyright © 2011-2022 走看看