import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
//定义树节点
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {val = x;}
}
//颜色标记法,第一次访问的节点为白色,第二次为灰色,
//用一个辅助栈,先添加右节点,在添加当前节点,再添加左节点
//递归处理
class Solution {
//定义颜色节点
class ColorNode {
TreeNode node;
String color;
ColorNode(TreeNode node, String color) {
this.node = node;
this.color = color;
}
}
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return new ArrayList<Integer>();
List<Integer> result = new ArrayList<>();
Stack<ColorNode> stack = new Stack<>();
//先把根节点放进去,并标记成白色
stack.push(new ColorNode(root, "white"));
while (!stack.isEmpty()) {
ColorNode current = stack.pop();
//如果当前节点为白色
if (current.color.equals("white")) {
//如果有右节点,则把右节点入栈,并标记成白色
if (current.node.right != null) {
stack.push(new ColorNode(current.node.right, "white"));
}
//当前节点入栈,并标记成灰色
stack.push(new ColorNode(current.node, "gray"));
//如果有左节点,则把左节点入栈,并标记成白色
if (current.node.left != null) {
stack.push(new ColorNode(current.node.left, "white"));
}
}
//如果当前节点为灰色,则把当前节点值添加到结果中
else {
result.add(current.node.val);
}
}
return result;
}
}
leetcode94. 二叉树的中序遍历
最新推荐文章于 2020-03-22 10:22:31 发布