二叉树的中序遍历
- https://leetcode.cn/problems/binary-tree-inorder-traversal/
描述
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例 1
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2
输入:root = []
输出:[]
示例 3
输入:root = [1]
输出:[1]
提示
- 树中节点数目在范围 [0, 100] 内
- -100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
Typescript 版算法实现
1 )方案 1
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function inorderTraversal(root: TreeNode | null): number[] {
const result: number[] = []
const isValid = (val: any) => val !== null;
const inorderHandler = (root: TreeNode | null) => {
if(!root) return result;
isValid(root.left) && inorderHandler(root.left);
isValid(root.val) && result.push(root.val);
isValid(root.right) && inorderHandler(root.right);
return result
}
return inorderHandler(root)
};
- 同前序遍历一样,这种是递归,只是把顺序交换了一下,这种还是深度优先递归
- 中序遍历特点:
- 对根节点的左子树进行中序遍历
- 访问根节点
- 对根节点的右子树进行中序遍历
- 记忆:左根右
2 )方案 2
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function inorderTraversal(root: TreeNode | null): number[] {
const result: number[] = [];
function dfs(node: TreeNode | null) {
if (!node) return
dfs(node.left);
result.push(node.val);
dfs(node.right);
}
dfs(root);
return result;
};
- 这个是官方示例,和方案1区别不大,从函数名就知道是深度优先
- 因为是左根右,这个左的第一个,一定是从最深层的左,所以需要递归
3 )方案 3
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function inorderTraversal(root: TreeNode | null): number[] {
const result: number[] = [];
const stk: TreeNode[] = []; // 存放节点的栈
while (root || stk.length) {
// 一个while循环找到最深层的左叶子节点
while (root) {
stk.push(root); // 当前节点进栈保存,用于取根和右节点
root = root.left; // 先访问左节点
}
root = stk.pop(); // 左节点出栈
result.push(root.val); // 左节点先保存,这里可能是 左节点或根节点
root = root.right; // 右节点
}
return result;
};
- 这个也是官方提供的示例,这个是迭代的方式,使用了栈来处理的
- 递归的本质就是栈,但是递归的栈可能很多,这里用了一个栈来管理节点
- 在内层的while循环会先找到最深层的左节点,因为栈的特性是先进后出
- 当最底层的左叶子出栈后,栈顶元素就是根节点了,之后去访问右叶子节点
- 这个是核心思想
Python3 版算法实现
1 )方案 1 递归版
# 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]:
result = []
def inorderHandler(node: Optional[TreeNode]):
if not node:
return
inorderHandler(node.left)
result.append(node.val)
inorderHandler(node.right)
inorderHandler(root)
return result
2 )方案 1 递归优化版
# 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]:
result = []
def dfs(node: Optional[TreeNode]):
if not node:
return
dfs(node.left)
result.append(node.val)
dfs(node.right)
dfs(root)
return result
3 )方案 迭代版
# 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]:
result = []
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
result.append(root.val)
root = root.right
return result
Golang 版算法实现
1 )方案 1 递归版
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
var result []int
inorderHandler(root, &result)
return result
}
func inorderHandler(root *TreeNode, result *[]int) {
if root == nil {
return
}
inorderHandler(root.Left, result)
*result = append(*result, root.Val)
inorderHandler(root.Right, result)
}
2 )方案 1 递归优化版
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
var result []int
dfs(root, &result)
return result
}
func dfs(node *TreeNode, result *[]int) {
if node == nil {
return
}
dfs(node.Left, result)
*result = append(*result, node.Val)
dfs(node.Right, result)
}
3 )方案 迭代版
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
result := []int{}
stack := []*TreeNode{}
for root != nil || len(stack) > 0 {
for root != nil {
stack = append(stack, root)
root = root.Left
}
root = stack[len(stack)-1]
stack = stack[:len(stack)-1]
result = append(result, root.Val)
root = root.Right
}
return result
}
1万+



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



