• Java for LeetCode 102 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]
    ]
    

    解题思路:

    前序遍历(BFS),使用一个Queue存储每层元素即可,JAVA实现如下:

        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> list = new ArrayList<List<Integer>>();
    		if (root == null)
    			return list;
    		Queue<TreeNode> queue = new LinkedList<TreeNode>();
    		queue.add(root);
    		while (queue.size() != 0) {
    			List<Integer> alist = new ArrayList<Integer>();
    			for (TreeNode child : queue)
    				alist.add(child.val);
    			list.add(new ArrayList<Integer>(alist));
    			Queue<TreeNode> queue2=queue;
    			queue=new LinkedList<TreeNode>();
    			for(TreeNode child:queue2){
    				if (child.left != null)
    					queue.add(child.left);
    				if (child.right != null)
    					queue.add(child.right);
    			}
    		}
    		return list;
        }
    
  • 相关阅读:
    Python 基础(二)
    Python 入门
    DNS
    PXE自动化安装CentOS7和CentOS6
    AIDE及sudo应用
    SSH应用
    KickStart自动化安装Linux
    初见鸟哥
    数组ARRAY
    SSH用法
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4523689.html
Copyright © 2020-2023  润新知