前序非递归遍历:
leetcode 144 https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
统一版:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<>();
TreeNode r = root;
while (!stack.isEmpty() || r != null) {
if (r != null) {
stack.push(r);
list.add(r.val);
r = r.left;
}
else {
r = stack.pop(); //注意写r
r = r.right;
}
}
return list;
}
}
简洁版:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) return new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<>();
TreeNode r = root;
stack.push(r);
while (!stack.isEmpty()) {
r = stack.pop();
list.add(r.val);
if (r.right != null)
stack.push(r.right);
if (r.left != null)
stack.push(r.left);
}
return list;
}
}
中序非递归遍历:
leetcode 94 https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
统一版:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<>();
TreeNode r = root;
while (!stack.isEmpty() || r != null) {
if (r != null) {
stack.push(r);
r = r.left;
}
else {
r = stack.pop(); //注意写r
list.add(r.val);
r = r.right;
}
}
return list;
}
}
后序非递归遍历:
leetcode 145 https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
统一版:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<>();
TreeNode r = root;
TreeNode flag = null; //用于标记已添加到list的右节点
while (!stack.isEmpty() || r != null) {
if (r != null) {
stack.push(r);
r = r.left;
}
else {
r = stack.peek();
if (r.right == null || r.right == flag) {
list.add(r.val);
flag = r;
stack.pop();
r = null; //这是下一次循环回到上一个节点的关键
}
else
r = r.right;
}
}
return list;
}
}
简洁版:
只是将前序遍历的顺序更改了,然后逆序添加到List,实际访问结点的顺序不是后序遍历的顺序。
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) return new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<>();
TreeNode r = root;
stack.push(r);
while (!stack.isEmpty()) {
r = stack.pop();
list.add(0, r.val); //每个都插入到第一位,使整个链表最后逆序输出
if (r.left != null)
stack.push(r.left);
if (r.right != null)
stack.push(r.right);
}
return list;
}
}