标签:Binary cur level List travel Level Tree result import
1. 题目描述
2. Solution 1
1、思路分析
使用BFS+递归,逐层遍历树,若当前层level为奇数,头插结点;若当前level为偶数,尾插结点。
2、代码实现
package Q0199.Q0103BinaryTreeZigzagLevelOrderTraversal;
import DataStructure.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Solution {
/*
1. O(n) solution by using LinkedList along with ArrayList.
So insertion in the inner list and outer list are both O(1),
2. Using BFS and creating new lists when needed.
*/
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
travel(root, result, 0);
return result;
}
private void travel(TreeNode cur, List<List<Integer>> result, int level) {
if (cur == null) return;
if (result.size() <= level) result.add(new LinkedList<>());
List<Integer> curLevel = result.get(level);
if (level % 2 == 0) curLevel.add(cur.val); // level为偶数,尾插
else curLevel.add(0, cur.val); // level为奇数,头插
travel(cur.left, result, level + 1);
travel(cur.right, result, level + 1);
}
}
/*
中文社区,另解: 1. 正常层次遍历;2. 遍历1. 结果, level为奇数,reverse.
*/
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)
标签:Binary,cur,level,List,travel,Level,Tree,result,import 来源: https://www.cnblogs.com/junstat/p/16252055.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。