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));
结果: