阅读 178

leetcode 94. Binary Tree Inorder Traversal (python)

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

描述

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

Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]
复制代码

Example 2:

Input: root = []
Output: []
复制代码

Example 3:

Input: root = [1]
Output: [1]
复制代码

Example 4:

Input: root = [1,2]
Output: [2,1]
复制代码

Example 5:

Input: root = [1,null,2]
Output: [1,2]
复制代码

Note:

The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
复制代码

解析

根据题意,就是给出了一个二叉树的根节点 root ,然后要求我们使用中序遍历这棵树,并将按照中序遍历顺序的节点按顺序放入列表中返回。这道题很简单,一般这种中序遍历的题,直接使用递归遍历每个节点就可以了。

解答

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        result = []
        def dfs(root):
            if not root:
                return 
            dfs(root.left)
            result.append(root.val)
            dfs(root.right)
        dfs(root)            
        return result
        	      
		
复制代码

运行结果

Runtime: 20 ms, faster than 54.47% of Python online submissions for Binary Tree Inorder Traversal.
Memory Usage: 13.5 MB, less than 48.15% of Python online submissions for Binary Tree Inorder Traversal.
复制代码

解析

当然了还可以使用栈来迭代遍历每个节点。

解答

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution(object):
    def inorderTraversal(self, root):
        res, stack = [], []
        while True:
            while root:
                stack.append(root)
                root = root.left
            if not stack:
                return res
            node = stack.pop()
            res.append(node.val)
            root = node.right
复制代码

运行结果

Runtime: 46 ms, faster than 5.99% of Python online submissions for Binary Tree Inorder Traversal.
Memory Usage: 13.6 MB, less than 19.47% of Python online submissions for Binary Tree Inorder Traversal.
  
复制代码

原题链接:leetcode.com/problems/bi…

您的支持是我最大的动力

文章分类
后端
文章标签