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]

]

题目非常简单,将二叉树按层的顺序依次输出

解决思路:

用层序遍历的思路不断的获得节点的值就行了

代码:

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
    	List<List<Integer>> result = new ArrayList<>();
    	List<TreeNode> level = new ArrayList<Solution.TreeNode>();
        
    	level.add(root);
    	while(!level.isEmpty() && level.get(0) != null){
    		List<Integer> currentLevel = new ArrayList<Integer>();
    		List<TreeNode> nextLevel = new ArrayList<Solution.TreeNode>();
    		
    		for(TreeNode node : level){
    			currentLevel.add(node.val);
    			if(node.left != null) nextLevel.add(node.left);
    			if(node.right != null) nextLevel.add(node.right);
    		}
    		result.add(currentLevel);
    		level = nextLevel;
    	}
    	
        return result;
    }
}


你可能感兴趣的:(LeetCode题解:Binary Tree Level Order Traversal)