今天为大家总结了二叉树前中后序遍历的递归与迭代解法:
1. 前序遍历
递归
List list=new ArrayList<>();public ListpreOrder(TreeNode root ){if(root == null)return list;
list.add(root.val);
preOrder(root.left);
preOrder(root.right);return list;
}
非递归
public ListpreOrder2(TreeNode root){
if(root==null)
return new ArrayList<>();
List list = new ArrayList<>();
Stack stack = new Stack<>();
stack.push(root);while (!stack.isEmpty()){
TreeNode tmp = stack.pop();
list.add(tmp.val);if(tmp.right!=null)
stack.push(tmp.right);if(tmp.left!=null)
stack.push(tmp.left);
}return list;
}
2. 中序遍历
递归
List list=new ArrayList<>();public ListinOrder(TreeNode root ){if(root == null)return list;
inOrder(root.left);
list.add(root.val);
inOrder(root.right);return list;
}
非递归
public ListinOrder2(TreeNode root) {
List list = new ArrayList<>();
Stack stack = new Stack<>();
TreeNode cur = root;while(cur!=null || !stack.empty()){while(cur!=null){
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
list.add(cur.val);
cur = cur.right;
}return list;
}
3. 后序遍历
递归
public ListpostOrder(TreeNode root ){
if(root == null)
return list;
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
return list;
}
非递归一
public ListpostOrder2(TreeNode root){
if(root == null)
return new ArrayList<>();
List list = new ArrayList<>();
Stack stack = new Stack<>();
stack.push(root);while (!stack.isEmpty()){
TreeNode tmp = stack.pop();
list.add(tmp.val);if(tmp.left!=null)
stack.push(tmp.left);if(tmp.right!=null)
stack.push(tmp.right);
}
Collections.reverse(list);return list;
}
非递归二
public ListpostOrder3(TreeNode root) {
List ans = new ArrayList<>();
Stack stack = new Stack<>();
TreeNode cur = root;while (!stack.isEmpty() || cur != null) {if (cur != null && cur.left != null) {
stack.push(cur);
TreeNode left = cur.left;
cur.left = null;
cur = left;
} else if (cur != null && cur.right != null) {
stack.push(cur);
TreeNode right = cur.right;
cur.right = null;
cur = right;
} else if (cur.left == null && cur.right == null) {
ans.add(cur.val);
cur = stack.isEmpty() ? null : stack.pop();
}
}return ans;
}
关注微信公众号“算法岗从零到无穷”,更多算法知识点告诉你。