zoukankan      html  css  js  c++  java
  • 94. Binary Tree Inorder Traversal

    94. Binary Tree Inorder Traversal

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

    For example:
    Given binary tree [1,null,2,3],

       1
        
         2
        /
       3
    

    return [1,3,2].

    该题是做树的中序遍历,下面分别是递归解法和非递归解法:

    递归解法:

    class Solution(object):
        def inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if not root:
                return []
            return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)

     非递归解法:

    class Solution(object):
        def inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if not root:
                return []
            stack = []
            node = root
            result = []   
            while node or len(stack) > 0:
                while node:
                    stack.append(node)
                    node = node.left
                node = stack.pop()
                result.append(node.val)
                node = node.right
            return result
  • 相关阅读:
    八、分组
    七、select使用
    六、SQL基础应用
    五、修改MySQL密码
    side Effect
    js函数式编程
    React生命周期
    Portals
    git使用技巧
    函数式编程
  • 原文地址:https://www.cnblogs.com/bubbleStar/p/6359032.html
Copyright © 2011-2022 走看看