遍历
先序遍历
递归
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
pre(root,res);
return res;
}
public void pre(TreeNode root,List<Integer> res){
if(root!=null){
res.add(root.val);
pre(root.left,res);
pre(root.right,res);
}
}
非递归
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
Stack<TreeNode> stack = new Stack();
while(!stack.isEmpty()||root!=null){
if(root!=null){
res.add(root.val);
stack.push(root);
root=root.left;
}else{
root=stack.pop().right;
}
}
return res;
}
中序遍历
递归
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
mid(root,res);
return res;
}
public void mid(TreeNode root,List<Integer> res){
if(root!=null){
mid(root.left,res);
res.add(root.val);
mid(root.right,res);
}
}
非递归
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty()||root!=null){
if(root!=null){
stack.push(root);
root = root.left;
}else{
TreeNode index = stack.pop();
res.add(index.val);
root = index.right;
}
}
return res;
}
后序遍历
递归
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
mid(root,res);
return res;
}
public void mid(TreeNode root,List<Integer> res){
if(root!=null){
mid(root.left,res);
mid(root.right,res);
res.add(root.val);
}
}
非递归
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> res = new ArrayList();
Stack<TreeNode> stack = new Stack();
TreeNode pre = null;
while(!stack.isEmpty()||root!=null){
while(root!=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.right==null||root.right==pre){
res.add(root.val);
pre = root;
root=null;
}else{
stack.push(root);
root = root.right;
}
}
return res;
}
层序遍历
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root!=null){
queue.offer(root);
}
while(!queue.isEmpty()){
int n = queue.size();
List<Integer> index = new ArrayList();
for(int i = 0;i < n;i++){
TreeNode p = queue.poll();
index.add(p.val);
if(p.left!=null){
queue.offer(p.left);
}
if(p.right!=null){
queue.offer(p.right);
}
}
res.add(index);
}
return res;
}