Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null){
while(root != null){
visit(根节点)
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
visit(根节点)
root = root.right;
}
//观察可知 后序遍历为 左右根 ,逆序是 根右左,而先序遍历是 根左右
//所以只需要简单的改造先序遍历,使其变为根右左
//然后将访问结果reverse即为后序遍历结果
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
list.add(root.val);
stack.push(root);
root = root.right;
}
root = stack.pop();
root = root.left;
}
Collections.reverse(list);
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList();
TreeNode lastVisitedNode = null;
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode topNode = stack.peek();
if (topNode.right != null && topNode.right != lastVisitedNode) root = topNode.right;
else {
stack.pop();
//visit(node) -- list.add(topNode.val);
lastVisitedNode = topNode;
}
}
return list
原文:https://www.cnblogs.com/INnoVationv2/p/15221468.html