Leetcode 94. Binary Tree Inorder Traversalt (二叉树中序遍历)

原题

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Reference Answer

思路分析

直接按照正常中序遍历走就好了,递归做,省事。

My Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        
        res = []
        self.helper(root, res)
        return res
        
        
    def helper(self, root, res):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return
        else:
            self.helper(root.left, res)
            res.append(root.val)
            self.helper(root.right, res)

        

Reference Code
中序遍历的访问顺序为『先左再根后右』,递归版最好理解,递归调用时注意返回值和递归左右子树的顺序即可。

Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        this.val = val
        this.left, this.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree.
    @return: Inorder in ArrayList which contains node values.
    """
    def inorderTraversal(self, root):
        if root is None:
            return []
        else:
            return self.inorderTraversal(root.left) + [root.val] \
                              + self.inorderTraversal(root.right)
  

Note:

  • 直接用递归做吧,省事,参考答案的最省事,不过有一点要注意就是 [] 使用,以及 + 的使用,这个是直接返回一个list,如果是范围[[], [], []...],就不能再直接这样使用。

参考资料

[1] https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73026

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84673526