先用递归法写一下二叉树的遍历,再用迭代法。
递归法:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
preorder(root, res);
return res;
}
//前序遍历
public void preorder(TreeNode root, List<Integer> arr){
if(root == null) return;
arr.add(root.val);
preorder(root.left, arr);
preorder(root.right,arr);
}
//后序遍历
public void postorder(TreeNode root, List<Integer> arr){
if(root == null) return;
postorder(root.left, arr);
postorder(root.right,arr);
arr.add(root.val);
}
//中序遍历
public void inorder(TreeNode root, List<Integer> arr){
if(root == null) return;
inorder(root.left, arr);
arr.add(root.val);
inorder(root.right,arr);
}
}
迭代法:
//前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Deque<TreeNode> st = new LinkedList<>();
List<Integer> res = new ArrayList<>();
if(root == null) return res;
st.addLast(root);
while(!st.isEmpty()){
TreeNode node = st.pollLast();
res.add(node.val);
if(node.right != null) st.addLast(node.right);
if(node.left != null) st.addLast(node.left);
}
return res;
}
}
//中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Deque<TreeNode> st = new LinkedList<>();
List<Integer> res = new ArrayList<>();
if(root == null) return res;
TreeNode cur = root;
while(!st.isEmpty() || cur != null){
//优先处理录入左节点访问到根部,然后出栈后再处理右节点
if(cur != null){
st.addLast(cur);
cur = cur.left;
} else {
cur = st.pollLast();
res.add(cur.val);
cur = cur.right;
}
}
return res;
}
}
//后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Deque<TreeNode> st = new LinkedList<>();
List<Integer> res = new ArrayList<>();
if(root == null) return res;
st.addLast(root);
while(!st.isEmpty()){
TreeNode node = st.pollLast();
res.add(node.val);
if(node.left != null) st.addLast(node.left);
if(node.right != null) st.addLast(node.right);
}
Collections.reverse(res);
return res;
}
}
后序遍历是左右中,前序遍历的中左右,所以后序遍历的步骤是:
修改前序遍历代码,变成中右左放入res数组,然后反转数组就可以了
迭代法统一模板
//中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Deque<TreeNode> st = new LinkedList<>();
List<Integer> res = new ArrayList<>();
if(root == null) return res;
st.addLast(root);
while(!st.isEmpty() ){
TreeNode cur = st.peekLast();
if(cur != null){
st.pollLast();
if(cur.right != null) st.addLast(cur.right); //右
st.addLast(cur); //中
st.addLast(null); //左
if(cur.left != null) st.addLast(cur.left);
} else {
st.pollLast();
cur = st.pollLast();
res.add(cur.val);
}
}
return res;
}
}
只需要改变左中右的顺序即可