二叉树的遍历
①、前序遍历
给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
代码:
public List<Integer> preorderTraversal(TreeNode root) {
// 递归
List<Integer> res = new ArrayList<>();
preorder(root,res);
return res;
//迭代
// if(root == null) return new ArrayList<Integer>();
// List<Integer> res = new ArrayList<Integer>();
// Stack<TreeNode> stack = new Stack<>();
// stack.push(root);
// while(!stack.isEmpty()){
// TreeNode tmp = stack.pop();
// res.add(tmp.val);
// if(tmp.right != null) stack.push(tmp.right);
// if(tmp.left != null) stack.push(tmp.left);
// }
// return res;
}
public void preorder(TreeNode root,List<Integer> res){
if(root == null) return;
res.add(root.val);
preorder(root.left,res);
preorder(root.right,res);
}
②、中序遍历
给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
代码:
public List<Integer> inorderTraversal(TreeNode root) {
//递归
// List<Integer> res = new ArrayList<>();
// inorder(root,res);
// return res;
//迭代
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
if(cur != null){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
}else{
cur = stack.pop();
res.add(cur.val);
cur = cur.right;
}
}
return res;
}
// public void inorder(TreeNode root,List<Integer> res){
// if(root == null) return;
// inorder(root.left,res);
// res.add(root.val);
// inorder(root.right,res);
// }
③、后序遍历
给你一棵二叉树的根节点 root
,返回其节点值的 后序遍历 。
代码:
public List<Integer> postorderTraversal(TreeNode root) {
// 递归
// List<Integer> res = new ArrayList<>();
// postorder(root,res);
// return res;
//迭代
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
if(root == null) return res;
stack.push(root);
while(!stack.isEmpty()){
TreeNode tmp = stack.pop();
res.add(tmp.val);
if(tmp.left != null) stack.push(tmp.left);
if(tmp.right != null) stack.push(tmp.right);
}
reverse(res);
return res;
}
// public void postorder(TreeNode root,List<Integer> res){
// if(root == null) return;
// postorder(root.left,res);
// postorder(root.right,res);
// res.add(root.val);
// }
public void reverse(List<Integer> res){
int left = 0;
int right = res.size() - 1;
while(left < right){
int tmp = res.get(left);
res.set(left,res.get(right));
res.set(right,tmp);
left++;
right--;
}
}