码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的层次遍历

时间:2017-01-23 23:50:06      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:思路   队列   system   sys   int   eve   test   bsp   util   

思路:队列

 

package com.zhaochao.tree;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
* Created by zhaochao on 17/1/23.
*/
public class LeverTraversal {


public ArrayList<List<Integer>> leverOrder(TreeNode root) {

ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();

if(root == null) {
return result;
}

Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);

while(!queue.isEmpty()) {
List<Integer> lever = new ArrayList<Integer>();
int size = queue.size();
for(int i = 0; i < size; i++) {
TreeNode head = queue.poll();
lever.add(head.val);
if(head.left != null) {
queue.add(head.left);
}
if(head.right != null) {
queue.add(head.right);
}
}
result.add(lever);
}

return result;
}

public static void main(String[] args) {

TreeNode root = new TreeNode(0);
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);

root.left = node1;
root.right = node2;
node2.left = node3;

LeverTraversal test = new LeverTraversal();
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
result = test.leverOrder(root);
for(int i = 0; i < result.size(); i++) {
List<Integer> tmp = new ArrayList<Integer>();
tmp = result.get(i);
for(int j = 0; j < tmp.size(); j++) {
System.out.print(tmp.get(j) + " ");
}
System.out.println();
}
}
}

二叉树的层次遍历

标签:思路   队列   system   sys   int   eve   test   bsp   util   

原文地址:http://www.cnblogs.com/superzhaochao/p/6345171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!