树的前序、中序、后序遍历本质上都可以认为是深度遍历。
那树的层序遍历是什么?
总之先写一下树的前序遍历的递归写法和迭代写法。
// 递归写法
public class Solution{
List<Integer> list = new ArrayList<>();
public List<Integer> pre(TreeNode node){
if (node == null) {
return list;
}
list.add(node.val);
if (node.left != null) {
pre(node.left);
}
if (node.right != null) {
pre(node.right);
}
return list;
}
}
非递归写法就是主动申请一个栈,来实现递归栈的效果。需要注意的是入栈的顺序,栈先进后出FILO。
public class Solution1{
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
public List<Integer> pre1(TreeNode node){
if (node == null) {
return list;
}
stack.push(node);
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);
}
}
return list;
}
}
中序遍历:
递归写法:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null){
return list;
}
if(root.left != null){
inorderTraversal(root.left);
}
list.add(root.val);
if(root.right != null){
inorderTraversal(root.right);
}
return list;
}
}
非递归写法:
public class Solution{
List<Integer> list = new List<>();
LinkedList<TreeNode> stack = new LinkedList<>();
public List<Integer> pre(TreeNode root){
if (root == null) {
return null;
}
stack.add(root);
while(!stack.isEmpty()){
TreaNode node = stack.pollLast();
list.add(node.val);
if (node.left != null) {
stack.add(node.left);
}
if (node.right != null) {
stack.add(node.right);
}
}
return list;
}
}
层序遍历
就是一层一层的遍历整个树
递归写法:
class Solution {
List<List<Integer>> list = new ArrayList<List<Integer>>();
private void helper(List<List<Integer>> list, TreeNode node, int layer){
if(list.size() == layer){
list.add(new ArrayList<Integer>());
}
list.get(layer).add(node.val);
if(node.left != null){
helper(list, node.left, layer + 1);
}
if(node.right != null){
helper(list, node.right, layer + 1);
}
}
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null){
return list;
}
helper(list,root,0);
return list;
}
}
非递归写法:
class Solution {
List<List<Integer>> list = new ArrayList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null){
return list;
}
queue.add(root);
int level = 0;
while(!queue.isEmpty()){
list.add(new ArrayList());
int length = queue.size();
for(int i = 0;i < length; i++){
TreeNode node = queue.remove();
list.get(level).add(node.val);
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
level++;
}
}
}