首页 > 代码库 > [LeetCode][Java] Binary Tree Level Order Traversal

[LeetCode][Java] Binary Tree Level Order Traversal

题目:

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

题意:

给定一棵二叉树,依照层顺序遍历二叉树全部的节点(即 从左向右 一层层地)

比方,给定二叉树{3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7
返回它的层遍历为:

[
  [3],
  [9,20],
  [15,7]
]

算法分析:

该题是对二叉树进行层次优先遍历,层次遍历主要採用队列的形式进行存储,通过将每一个节点的左孩子和右孩子放入队列中,然后每次从队列中取出元素就可以。比較好理解,直接上代码了。

AC代码:

public class Solution 
{
     private static TreeNode root;
	 public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) 
	 {  
	        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();  
	        if (root == null)
	        {  
	            return res;  
	        }  
	        ArrayList<Integer> tmp = new ArrayList<Integer>();  
	        Queue<TreeNode> queue = new LinkedList<TreeNode>();  
	        queue.offer(root);  
	        int num;  
	        boolean reverse = false;  
	        while (!queue.isEmpty())
	        {  
	            num = queue.size();  //每次通过这个确定终于的出队数目
	            tmp.clear();  
	            for (int i = 0; i < num; i++) //队列中出1个父。进两个子;出2个父,进4个子;出4个父。进8个子
	            {  
	                TreeNode node = queue.poll();  
	                tmp.add(node.val);  
	                if (node.left != null)  
	                    queue.offer(node.left);  
	                if (node.right != null)  
	                    queue.offer(node.right);  
	            }  

	            res.add(new ArrayList<Integer>(tmp));  
	        }  
	        return res;  
	  }  
}

[LeetCode][Java] Binary Tree Level Order Traversal