来自北大算法课的Leetcode题解:94. 二叉树的中序遍历

代码仓库Github | Leetcode solutions @doubleZ0108 from Peking University.

  • 解法1(T90% S79%):递归,先递归左子树,再把跟的值加入全局结果数组,最后把递归右子树

  • 解法2(T99% S93%):迭代,大致思想就是一左到底,到最左边后输出叶节点值,然后回退到父节点,输出父节点的值,然后转移到右子树继续重复以上操作。具体实现:由于需要保存一连串父节点因此需要一个栈,首先while一左到底将所有父节点压栈,到左底之后输出左子树的值,然后前进到右子树,即将右子树压栈继续外层循环,但右子树可能为空,因此需要不断循环直至右子树不为空,期间把这些节点的值也输出

  • 🌰一些测试样例

    [1,null,2,3]   # 左子树为空
    [3,2,null,1]   # 左单枝树
    
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        # 解法2 迭代
        res = []
        
        stack = [root]
        while stack:
            move = stack.pop()
            while move and move.left:
                stack.append(move)
                move = move.left
            if move: res.append(move.val)
            while stack and not move.right:
                move = stack.pop()
                res.append(move.val)
            if move and move.right:
                stack.append(move.right)

        return res
    

    def otherSolution(self, root):
        # 解法1 递归
        res = []
        def inorder(root):
            if not root: return
            inorder(root.left)
            res.append(root.val)
            inorder(root.right)
        inorder(root)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

doubleZ0108

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值