[leetcode] Binary Tree Level Order Traversal
Posted Lin.B
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。
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,null,null,15,7]
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
1 class Solution { 2 public List<List<Integer>> levelOrder(TreeNode root) { 3 List<List<Integer>> res = new ArrayList<>(); 4 if ( root == null ) return res; 5 Queue<TreeNode> queue = new LinkedList<>(); 6 queue.offer(root); 7 while ( !queue.isEmpty() ){ 8 int size = queue.size(); 9 List<Integer> list = new ArrayList<>(); 10 for ( int i = 0 ; i < size ; i ++ ){ 11 TreeNode t = queue.poll(); 12 list.add(t.val); 13 if ( t.left != null ) queue.offer(t.left); 14 if ( t.right != null ) queue.offer(t.right); 15 } 16 res.add(list); 17 } 18 return res; 19 } 20 }
运行时间3ms。
Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
分析:题目翻译一下:倒着层次遍历一颗二叉树
1 public List<List<Integer>> levelOrder(TreeNode root) { 2 List<List<Integer>> res = new ArrayList<>(); 3 Queue<TreeNode> queue = new LinkedList<>(); 4 queue.offer(root); 5 while ( !queue.isEmpty() ){ 6 int size = queue.size(); 7 List<Integer> list = new ArrayList<>(); 8 for ( int i = 0 ; i < size ; i ++ ){ 9 TreeNode t = queue.poll(); 10 list.add(t.val); 11 if ( t.left != null ) queue.offer(t.left); 12 if ( t.right != null ) queue.offer(t.right); 13 } 14 res.add(list); 15 } 16 Collections.reverse(res); 17 return res; 18 }
思路二:将层的结果放入到一个stack中,最后读取stack中的数据也可以实现倒序。就不写代码了。
以上是关于[leetcode] Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode] construct-binary-tree-from-inorder-and-postorder-
[LeetCode226]Invert Binary Tree
[Leetcode] Binary tree-- 606. Construct String from Binary Tree
[Leetcode] Binary search tree --Binary Search Tree Iterator
Leetcode[110]-Balanced Binary Tree
[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree