# 树的理解（三）：遍历

## 层次遍历

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
int count = q.size();   //每层的节点数
List<Integer> list = new ArrayList<>();
while(count > 0) {
TreeNode cur = q.poll();
if(cur.left != null)
q.offer(cur.left);
if(cur.right != null)
q.offer(cur.right);
count--;
}
}
return res;
}
}

## 二叉树的层平均值

https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/

class Solution {
private List<Double> res = new ArrayList<>();
public List<Double> averageOfLevels(TreeNode root) {
if(root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
int count = q.size();
double sum = 0;
int cur_count =  count;
while(count-- > 0) {
TreeNode cur = q.poll();
sum += cur.val;
if(cur.left != null) q.offer(cur.left);
if(cur.right != null) q.offer(cur.right);
}
}
return res;
}
}

## 找树左下角的值

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

class Solution {
public int findBottomLeftValue(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int res = root.val;
while(!q.isEmpty()) {
int count = q.size();
int flag = 0;
while(count-- > 0) {
TreeNode cur = q.poll();
if(flag == 0) {
res = cur.val;
flag = 1;
}
if(cur.left != null) q.offer(cur.left);
if(cur.right != null) q.offer(cur.right);
}
}
return res;
}
}

## 二叉树的前序遍历（非递归）

public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null){
while(root != null) {
stack.push(root);
root = root.left;
}
TreeNode cur = stack.pop();
root = cur.right;
}
return list;
}

## 二叉树的中序遍历（非递归）

public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null) {
while(root != null) {
stack.push(root);
root = root.left;
}
TreeNode cur = stack.pop();
root = cur.right;
}
return list;
}

## 二叉树的后序遍历（非递归）

public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> visited = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = root;
while(!stack.isEmpty() || root != null) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.peek();
if(root.right == pre || root.right == null) {
stack.pop();
pre = root;
root = null;
}else
root = root.right;
}
return visited;
}

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客