Leet Code OJ 102. Binary Tree Level Order Traversal [Difficulty: Easy]
Posted Lnho
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leet Code OJ 102. Binary Tree Level Order Traversal [Difficulty: Easy]相关的知识,希望对你有一定的参考价值。
题目:
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},
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
翻译:
给定一个二叉树,返回它的节点值的层序遍历(即从左到右,一层一层的)。
分析:
采用递归的方式,先返回根节点,然后递归调用左右节点,把左右节点的结果进行按照题目要求的形式拼装。另外注意一些递归过程中节点为空的情况。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result=new ArrayList<>();
if(root==null){
return result;
}
List<Integer> one=new ArrayList<>();
one.add(root.val);
result.add(one);
List<List<Integer>> left=levelOrder(root.left);
List<List<Integer>> right=levelOrder(root.right);
for(int i=0;i<left.size()||i<right.size();i++){
List<Integer> item=new ArrayList<>();
if(i<left.size()){
for(Integer k:left.get(i)){
item.add(k);
}
}
if(i<right.size()){
for(Integer k:right.get(i)){
item.add(k);
}
}
result.add(item);
}
return result;
}
}
以上是关于Leet Code OJ 102. Binary Tree Level Order Traversal [Difficulty: Easy]的主要内容,如果未能解决你的问题,请参考以下文章
Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]
Leet Code OJ 1. Two Sum [Difficulty: Easy]
Leet Code OJ 223. Rectangle Area [Difficulty: Easy]
Leet Code OJ 338. Counting Bits [Difficulty: Easy]