标签:遍历 TreeNode lists depth 二叉树 锯齿形 test new root
flag
软件学院大三党,每天一道算法题,第十八天
题目介绍
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
思路
迭代:采用经过加工的广度遍历,引入depth层数,逐层将元素放入链表(奇数层插入到尾部,偶数层插入到头部),用队列的长度代表每层的元素个数,即内层循环的次数,再将下一层元素放入队列。
递归:类似深度优先遍历
关键代码
迭代
public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> lists=new ArrayList<>();
if(root==null)
return lists;
Queue<TreeNode>queue=new LinkedList<>();
queue.add(root);
int depth=0;
while (!queue.isEmpty()){
List<Integer> tmp = new LinkedList<>();
int count=queue.size();
for(int i=0;i<count;i++){
TreeNode temp=queue.poll();
if(depth%2==0)
tmp.add(temp.val);
else//从首部添加元素
tmp.add(0,temp.val);
if(temp.left!=null)
queue.add(temp.left);
if(temp.right!=null)
queue.add(temp.right);
}
lists.add(tmp);
depth++;
}
return lists;
}
递归
public static List<List<Integer>> zigzagLevelOrder2(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
helper(res, root, 0);
return res;
}
public static void helper(List<List<Integer>> lists, TreeNode root, int depth) {
if (root == null)
return;
if (lists.size() == depth)
lists.add(new LinkedList<>());
if (depth % 2 == 0)
lists.get(depth).add(root.val);
else
lists.get(depth).add(0, root.val);
helper(lists, root.left, depth + 1);
helper(lists, root.right, depth + 1);
}
测试
TreeNode test=new TreeNode(1);
test.left=new TreeNode(2);
test.left.right=new TreeNode(4);
test.right=new TreeNode(9);
test.right.left=new TreeNode(4);
test.right.right=new TreeNode(3);
List<List<Integer>>l=zigzagLevelOrder(test);
for(int i=0;i<l.size();i++)
System.out.println(l.get(i));
结果:
标签:遍历,TreeNode,lists,depth,二叉树,锯齿形,test,new,root 来源: https://blog.csdn.net/weixin_44076848/article/details/102757204
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。