102. Binary Tree Level Order Traversal
Given the root
of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Example 1:
Example 2:
Example 3:
Solution:
Tree里头关于层有关的请优先想到BFS, queue
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int index = 0;
dfs(root, index, result);
return result;
}
private void dfs(TreeNode root, int index, List<List<Integer>> result){
if (root == null){
return;
}
if (index >= result.size()){
result.add(new ArrayList<Integer>());
}
result.get(index).add(root.val);
dfs(root.left, index + 1, result);
dfs(root.right, index + 1, result);
}
}
// TC: O(n)
// SC: O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null){
return result;
}
int index = 0;
dfs(root, index, result);
return result;
}
private void dfs (TreeNode root, int index, List<List<Integer>> result){
if (root == null){
return;
}
if (index >= result.size()){
result.add(new ArrayList<Integer>());
}
result.get(index).add(root.val);
dfs(root.left, index + 1, result);
dfs(root.right, index + 1, result);
}
}
// TC: O(n)
// SC: O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null){
return result;
}
int index = 0;
DFS(root, index, result);
return result;
}
private void DFS(TreeNode root, int index, List<List<Integer>> result){
// base case
if (root == null){
return;
}
if (index >= result.size()){
result.add(new ArrayList<Integer>());
}
result.get(index).add(root.val);
DFS(root.left, index + 1, result);
DFS(root.right, index +1 , result);
}
}
// TC: O(n)
// SC: O(n)
Tree的题 代码答案不难理解, 单纯让你想思路 感觉很容易无从下手的感觉 -> 但基本上都要遍历