• 二叉树总结及部分Lintcode题目分析 1


    1. 遍历问题 Preorder / Inorder / Postorder

    preorder: root left right

    inorder: left root right

    postorder: left right root

    遇到二叉树的问题,就是一步步的拆分,最常用的就是Divide & Conquer的递归实现

    贴一个preorder的例子

    Definition of TreeNode:
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left, self.right = None, None
    """
    
    
    class Solution:
        """
        @param root: The root of binary tree.
        @return: Preorder in ArrayList which contains node values.
        """
        def preorderTraversal(self, root):
            result = []
            if root is None:
                return result
            result = [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
            return result
    
    2. 遍历问题的变形,比如Maximum Depth of Binary Tree,是同样的思想,从root出发的最深路径一定是左右子数最深路径的最大值。就可以一步步把树分拆下去。
     
    贴一个代码
     
    """
    Definition of TreeNode:
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left, self.right = None, None
    """
    class Solution:
        """
        @param root: The root of binary tree.
        @return: An integer
        """ 
        def maxDepth(self, root):
            depth = 0
            if root is None:
                return depth
            depth = max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
            return depth
                
    

     3. 继续进行延伸,在Balanced binary tree 的做法中可以应用 maxDepth的解法

    判断是否是balanced binary tree最直观的就是左右子树的高度差,对任意一个点来说的话 left - right > 1 则不是balanced

    """
    Definition of TreeNode:
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left, self.right = None, None
    """
    class Solution:
        """
        @param root: The root of binary tree.
        @return: True if this Binary tree is Balanced, or false.
        """
        def maxDepth(self, root):
            if root is None:
                return 0
            left = self.maxDepth(root.left)
            right = self.maxDepth(root.right)
            # at first, the abs is ignored and the operations when the maxdepth is calculated is wrong
            if left == -1 or right == -1 or abs(left - right) > 1:
                return -1
            return max(left, right) + 1
            
        def isBalanced(self, root):
            if root is None:
                return True
            return self.maxDepth(root) != -1
    
  • 相关阅读:
    HDU1496 Equations 卡时间第二题
    HDU3833 YY's new problem 卡时间第一题
    hiho1601最大分数 DP
    密码脱落
    hihoCoder
    王坚十年前的坚持,才有了今天世界顶级大数据计算平台MaxCompute
    SaaS加速器 I 商业中心:提供商业助力 共享商业成功
    发布SaaS加速器:我们不做SaaS,我们只做SaaS生态的推进者和守护者
    MaxCompute SQL 使用正则表达式选列
    MaxCompute如何对SQL查询结果实现分页获取
  • 原文地址:https://www.cnblogs.com/chercher/p/5682056.html
Copyright © 2020-2023  润新知