94. Binary Tree Inorder Traversal

Posted bubbleStar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于94. Binary Tree Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

94. Binary Tree Inorder Traversal

#Leetcode# 94. Binary Tree Inorder Traversal

(Tree)94.Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal