题目描述:
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
Java代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
class ColorNode {
TreeNode node;
String color;
public ColorNode(TreeNode node, String color) {
this.node = node;
this.color = color;
}
}
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null) return new ArrayList<>();
List<Integer> res = new ArrayList<>();
Stack<ColorNode> stack = new Stack<>();
stack.push(new ColorNode(root, "white"));
while(!stack.empty()) {
ColorNode cn = stack.pop();
if(cn.color.equals("white")) {
stack.push(new ColorNode(cn.node, "gray"));
if(cn.node.right != null) stack.push(new ColorNode(cn.node.right, "white"));
if(cn.node.left != null) stack.push(new ColorNode(cn.node.left, "white"));
} else {
res.add(cn.node.val);
}
}
return res;
}
}
网友评论