zoukankan      html  css  js  c++  java
  • 二叉树

    二叉树包含节点:一个节点包含节点值及子节点

    class TreeNode:
        def __init__(self,val =0, left = None, right = None):
            self.val = val
            self.left = left
            self.right = right
    
    # 给二叉树的根节点,返回节点值的前序遍历
    class Solution:
    
        # 前序遍历(根-左-右)
        def preorderTraversal(self, root: TreeNode) -> list:
            list = []
            def per(root):
                if not root:
                    return
                list.append(root.val)
                per(root.left)
                per(root.right)
            per(root)
            return list
    
        # 中序遍历(左-根-右)
        def preorder(self, root: TreeNode) -> list:
            list = []
            def per(root):
                if not root:
                    return
                per(root.left)
                list.append(root.val)
                per(root.right)
            per(root)
            return list
    
        # 后序遍历(左-根-右)
        def preorder_right(self, root: TreeNode) -> list:
            list = []
            def per(root):
                if not root:
                    return
                per(root.left)
                per(root.right)
                list.append(root.val)
    
            per(root)
            return list
    
        # 求二叉树的深度
        def maxDepth(self, root: TreeNode):
            if root is None: # 递归的终止条件:最后一个节点的子节点深度为0
                return 0
            else:
                # left_height = self.maxDepth(root.left)
                # right_height = self.maxDepth(root.right)
                # return max(left_height, right_height) + 1
                return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 # 每一个节点的深度都等于他的子节点+1
    
    
    
    
    
    
    s = Solution()
    r1 = TreeNode(1)
    r2 = TreeNode(2)
    r3 = TreeNode(3)
    r4 = TreeNode(4)
    r1.left = r2
    r1.right = r4
    r2.left = r3
    
    # s.preorderTraversal(r1)
    print(s.maxDepth(r1))
  • 相关阅读:
    自动化测试全聚合
    选择排序(JAVA实现)
    插入排序(JAVA实现)
    冒泡排序(JAVA实现)
    快速排序(java实现)
    Python+页面元素高亮源码实例
    (原创)Python 自动化测试框架详解
    Python+requests库 POST接口图片上传
    基于Python + requests 的web接口自动化测试框架
    python 创建mysql数据库
  • 原文地址:https://www.cnblogs.com/byy521/p/15098684.html
Copyright © 2011-2022 走看看