当前位置:   article > 正文

菜鸟扣代码第十六天:leetcode第94题--二叉树的中序遍历_为什么root 为 [1,null,2,3]

为什么root 为 [1,null,2,3]

题目描述:

给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
在这里插入图片描述

输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:

输入:root = []
输出:[]

代码:

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: TreeNode) -> List[int]:
        if root == None:
            return []
        stack = []
        res = []
        temp = root
        while temp or stack:
            if temp != None:
                stack.append(temp)
                temp = temp.left
            else:
                temp = stack.pop()
                res.append(temp.val)
                temp = temp.right
        return res
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

测试:

输入
[1,null,2,3]
输出
[1,3,2]
预期结果
[1,3,2]

思路:

二叉树的中序遍历是非常经典的题目,在这里借助栈来实现非递归的遍历方法。1.检查二叉树是否为空,if空则退出。2.else沿着左子树一直到左子树的最底部,并且移动过程中依次进栈。3.移动到左子树最低端后,开始出栈,一个节点出栈后,进入该节点的右子树,继续执行2 。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/50437
推荐阅读
相关标签
  

闽ICP备14008679号