一、题目描述
中序遍历
二、代码思路
递归 or 迭代
迭代我们使用颜色标记法来进行树的中序 前序 后序三种迭代遍历
- 将每个树的节点都用颜色标记,白色为未访问,灰色为已访问。
- 借助栈,判断栈弹出的节点,如果是白色,就把其右节点、本身、其左节点加入栈,如果是灰色就访问。
- 同理,针对前序遍历以 根 左 右 顺序来遍历,那么入栈的顺序也就是 右 左 根。
三、代码思路
package leetcode.lc20221211;
/*
* @author lzy
* @version 1.0
* */
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution01 {
List<Integer> res = new ArrayList<>();
class colorNode {
TreeNode node;
int color;
colorNode(TreeNode node, int color) {
this.node = node;
this.color = color;
}
}
//二叉树的中序遍历
//三色标记法
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return res;
}
Stack<colorNode> stack = new Stack<>();
stack.push(new colorNode(root, 0));
while (!stack.isEmpty()) {
colorNode node = stack.pop();
if (node.color == 0) {
if (node.node.right != null) {
stack.push(new colorNode(node.node.right, 0));
}
stack.push(new colorNode(node.node, 1));
if (node.node.left != null) {
stack.push(new colorNode(node.node.left, 0));
}
} else {
res.add(node.node.val);
}
}
return res;
}
//解法1: 递归形式的中序遍历
public void dfs(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
dfs(root.left);
}
res.add(root.val);
if (root.right != null) {
dfs(root.right);
}
}
}