94、二叉树的中序遍历
基本思想:
中序遍历,左中右,先访问的是二叉树顶部的节点,
然后一层一层向下访问,直到到达树左面的最底部,
再开始处理节点(也就是在把节点的数值放进result数组中),
这就造成了处理顺序和访问顺序是不一致的。
在使用迭代法写中序遍历,就需要设置一个当前节点来帮助访问节点,栈则用来处理节点上的元素。
代码:
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new LinkedList<>(); Stack<TreeNode> st = new Stack<>(); TreeNode cur = root; while (!st.empty() || cur != null) { if (cur != null){ st.push(cur); cur = cur.left; } else { cur = st.pop(); result.add(cur.val); cur = cur.right; } } return result; }
144、二叉树的前序遍历
具体实现:
前序遍历是中左右,每次先处理的是中间节点
先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子
这样出栈的时候才是中左右的顺序
// 前序遍历顺序:中-左-右,入栈顺序:中-右-左 class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null){ return result; } Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()){ TreeNode node = stack.pop(); result.add(node.val); if (node.right != null){ stack.push(node.right); } if (node.left != null){ stack.push(node.left); } } return result; } }
145、二叉树的后序遍历
具体实现:
前序遍历是中左右,后序遍历是左右中
只需要调整前序遍历的代码顺序,变成中右左的遍历顺序,然后翻转result数组,就变成了左右中了
// 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果 class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null){ return result; } Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()){ TreeNode node = stack.pop(); result.add(node.val); if (node.left != null){ stack.push(node.left); } if (node.right != null){ stack.push(node.right); } } Collections.reverse(result); return result; } }