LeetCode 94. Binary Tree Inorder Traversal(二叉树中序遍历)

原题

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]

Note:

Follow up: Recursive solution is trivial, could you do it iteratively?

题目:
给定一个二叉树,返回其中序遍历(注意中序遍历的英写法:inorder traversal

Reference Answer

思路分析

解题思路

  • 递归,定义helper函数
  • Divide & Conquer
  • 非递归
  1. (操作一)每一次从当前节点开始(第一次是root节点)遍历至最左节点,一次入栈;
  2. (操作二)pop出栈一个node,node.val加入到结果,然后看该node有没有右儿子;
  3. 有的话重复操作一;没有的话,继续pop出栈一个node,重复操作二;
# 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)

         

反思:

  1. 对函数声明输入一个list(如题中的res),无需子函数返回res,函数对res进行操作,会有直接效果,最终结果直接输入res即可;
  2. 二叉树遍历规则:先序:考察到一个节点后,即刻输出该节点的值,并继续遍历其左右子树。(根左右)
    中序:考察到一个节点后,将其暂存,遍历完左子树后,再输出该节点的值,然后遍历右子树。(左根右)
    后序:考察到一个节点后,将其暂存,遍历完左右子树后,再输出该节点的值。(左右根)

猜你喜欢

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