- 前序、中序、后序遍历采用深度优先思想
- 前序遍历【根-左-右】
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
digui(list,root);
return list;
}
public void digui(List<Integer> list,TreeNode root){
if(root==null) return;
list.add(root.val);
digui(list,root.left);
digui(list,root.right);
}
}
- 中序遍历【左-根-右】
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
digui(list,root);
return list;
}
public void digui(List<Integer> list,TreeNode root){
if(root==null) return;
digui(list,root.left);
list.add(root.val);
digui(list,root.right);
}
}
- 后序遍历【左-右-根】
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
digui(list,root);
return list;
}
public void digui(List<Integer> list,TreeNode root){
if(root==null) return;
digui(list,root.left);
digui(list,root.right);
list.add(root.val);
}
}
- 层序遍历采用广度优先思想
- 层序遍历
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> que = new LinkedList<>();
if(root==null) return new ArrayList<>();
que.offer(root);
List<List<Integer>> l1 = new ArrayList<>();
while(que.size()>0){
int size = que.size();
List<Integer> l2 = new ArrayList<>();
for(int i=0;i<size;i++){
TreeNode r = que.poll();
l2.add(r.val);
if(r.left!=null) que.offer(r.left);
if(r.right!=null) que.offer(r.right);
}
l1.add(l2);
}
return l1;
}
}