lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

    • 链表

    • 栈

    • 树

      • 94.二叉树的中序遍历
      • 100.相同的树
      • 101.对称二叉树
      • 226.翻转二叉树
      • 543. 二叉树的直径
  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • tree
2023-04-29

二叉树的中序遍历

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ (opens new window) 需要注意的点 树的遍历顺序 前序,父左右 中序,左父右 后序 ,左右父 1 递归 2.迭代

# Definition for a binary tree node.
# 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: Optional[TreeNode]) -> List[int]:

		res = []
		def dfs(root):
			if not root:
				return
			# 按照 左-打印-右的方式遍历	
			dfs(root.left)
			res.append(root.val)
			dfs(root.right)
		dfs(root)
		return res


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        stack =[]
        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                tmp = stack.pop()
                res.append(tmp.val)
                root = tmp.right
        
        return res
155.最小栈
100.相同的树

← 155.最小栈 100.相同的树→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式