94.二叉树的中序遍历
具体实现:
将访问的节点直接加入到栈中,但如果是出去过的节点则后面再放入一个空节点,
这样只有空节点弹出的时候,才将下一个节点放进结果集。
代码:
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new LinkedList<>(); TreeNode cur = root; if(cur != null) stack.push(cur); while (!stack.isEmpty()) { cur = stack.peek(); if (cur != null) { cur = stack.pop(); if (cur.right != null) stack.push(cur.right); stack.push(cur); stack.push(null); if (cur.left != null) stack.push(cur.left); } else { stack.pop(); cur = stack.pop(); result.add(cur.val); } } return result; } }
144.二叉树的前序遍历
代码:
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new LinkedList<>(); TreeNode cur = root; if(cur != null) stack.push(cur); while (!stack.isEmpty()) { cur = stack.peek(); if (cur != null) { cur = stack.pop(); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); stack.push(cur); stack.push(null); } else { stack.pop(); cur = stack.pop(); result.add(cur.val); } } return result; } }
145.二叉树的后序遍历
代码:
class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new LinkedList<>(); TreeNode cur = root; if(cur != null) stack.push(cur); while (!stack.isEmpty()) { cur = stack.peek(); if (cur != null) { cur = stack.pop(); stack.push(cur); stack.push(null); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); } else { stack.pop(); cur = stack.pop(); result.add(cur.val); } } return result; } }