zoukankan      html  css  js  c++  java
  • leetcode--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]
    ]

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        /**This is a simple problem.<br>
    	 * 
    	 * @param root --the root node of a tree
    	 * @return List of value of each level
    	 * @author Averill Zheng
    	 * @version 2016-06-03
    	 * @since JDK 1.7
    	 */
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer> > result = new ArrayList<List<Integer>>();
            if(root != null){
            	Queue<TreeNode> topLevel = new LinkedList<TreeNode>();
            	topLevel.add(root);
            	while(topLevel.peek() != null){
            		Queue<TreeNode> nextLevel = new LinkedList<TreeNode>();
            		List<Integer> value = new ArrayList<Integer>();
            		while(topLevel.peek() != null){
            			TreeNode node = topLevel.poll();
            			value.add(node.val);
            			if(node.left != null)
            				nextLevel.add(node.left);
            			if(node.right != null)
            				nextLevel.add(node.right);
            		}
            		result.add(value);
            		topLevel = nextLevel;
            	}
            }
            return result;    
        }
    }
    

      

  • 相关阅读:
    华为2016校园招聘上机笔试题
    android SQLite 使用
    handler
    fragment 给 activity 传数据
    activity 给 fragment 传递数据
    fragment (动态加载)
    fragment (静态)
    Java学习随笔之磨刀篇——环境搭建+问候世界
    Go语言设计哲学
    Ubuntu设置护眼程序
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3769738.html
Copyright © 2011-2022 走看看