zoukankan      html  css  js  c++  java
  • 144. Binary Tree Preorder Traversal

    Given a binary tree, return the preorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,2,3].

     该题是对树做前序遍历

    下面分别是递归,非递归,分治三种思路的解题结果

    #递归写法
    class Solution(object):
        
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if root is None:
                return []
            result = []
            self.traverse(root,result)
            return result
        def traverse(self,root,result):
            if root is None:
                return
            result.append(root.val)
            self.traverse(root.left,result)
            self.traverse(root.right,result)   
    #分治法
    class Solution(object):
        
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if root is None:
                return []
            result = []
            #分
            left = self.preorderTraversal(root.left)
            right = self.preorderTraversal(root.right)
            #治
            result.append(root.val)
            result.extend(left)
            result.extend(right)
            return result
    #非递归写法,用栈模拟
    class Solution(object):
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if root is None:
                return []
            stack = [root]
            preorder = []
            while stack:
                node = stack.pop()
                preorder.append(node.val)
                if(node.right):
                    stack.append(node.right)
                if(node.left):
                    stack.append(node.left)
            return preorder   
  • 相关阅读:
    中文转码问题总结
    Linux命令总结
    Maven实战系列文章目录
    JXL API总结
    docker 中安装mysql8之后无法远程连接的问题caching-sha2-password
    springboot查数据并以csv格式现在到本地
    aop
    java.lang.ClassNotFoundException: org.aspectj.lang.JoinPoint
    shiro框架中获取username、ip等信息
    cron
  • 原文地址:https://www.cnblogs.com/bubbleStar/p/6357630.html
Copyright © 2011-2022 走看看