给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
链接:https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xecaj6/
方法一:递归
知识点:
二叉树根节点的值:root.val
二叉树的左子树:root.left
二叉树的右子树:root.right
# 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]:
result = [] # 这个要写在自己定义的函数前面
def inorder(root):
if root == None:
return result
inorder(root.left)
result.append(root.val)
inorder(root.right)
inorder(root) # 这里要使用自己定义的函数,并传入参数
return result

方法二:迭代
本文详细解析了二叉树中序遍历的两种方法:递归和迭代。通过实例展示了如何从给定的二叉树[1,null,2,3]中获得正确的中序遍历结果[1,3,2]。文章提供了Python代码实现,帮助读者深入理解二叉树遍历算法。

283

被折叠的 条评论
为什么被折叠?



