怎么增加网站百度收录,做网站页面需要的资料,网站建设的方案计划,如何做网络营销宣传目录 题目1- 思路2- 实现⭐103. 二叉树的锯齿形层序遍历——题解思路 2- ACM实现 题目
原题连接#xff1a;103. 二叉树的锯齿形层序遍历 1- 思路
二叉树的层序遍历#xff0c;遇到奇数时#xff0c;利用 Collections.reverse() 翻转即可 2- 实现
⭐103. 二叉树的锯齿形层… 目录 题目1- 思路2- 实现⭐103. 二叉树的锯齿形层序遍历——题解思路 2- ACM实现 题目
原题连接103. 二叉树的锯齿形层序遍历 1- 思路
二叉树的层序遍历遇到奇数时利用 Collections.reverse() 翻转即可 2- 实现
⭐103. 二叉树的锯齿形层序遍历——题解思路 class Solution {public ListListInteger res new ArrayList();public ListListInteger zigzagLevelOrder(TreeNode root) {return Traversal(root);}public ListListInteger Traversal(TreeNode root){if(rootnull){return res;}// 借助 queueQueueTreeNode queue new LinkedList();queue.offer(root);// queue 不空int count 0;while(!queue.isEmpty()){int len queue.size();ListInteger path new ArrayList();while(len0){TreeNode node queue.poll();path.add(node.val);if(node.left!null){queue.offer(node.left);}if(node.right!null){queue.offer(node.right);}len--;}count;if(count%21){res.add(new ArrayList(path));}else{Collections.reverse(path);res.add(new ArrayList(path));}}return res;}
}2- ACM实现
public class levelTraversal {static class TreeNode{int val;TreeNode left;TreeNode right;TreeNode(){}TreeNode(int x){val x;}}public static TreeNode build(Integer[] nums){QueueTreeNode queue new LinkedList();TreeNode root new TreeNode(nums[0]);queue.offer(root);int index 1;while(!queue.isEmpty() indexnums.length){TreeNode node queue.poll();if(nums[index]!null indexnums.length){node.left new TreeNode(nums[index]);queue.offer(node.left);}index;if(nums[index]!null indexnums.length){node.right new TreeNode(nums[index]);queue.offer(node.right);}index;}return root;}static ListListInteger res new ArrayList();public static ListListInteger levelTraversal(TreeNode root){if(rootnull) {return res;}QueueTreeNode queue new LinkedList();queue.offer(root);int level 0;while(!queue.isEmpty()){ListInteger iterm new ArrayList();int len queue.size();while(len0){TreeNode node queue.poll();iterm.add(node.val);if(node.left!null){queue.offer(node.left);}if(node.right!null){queue.offer(node.right);}len--;}if(level%21) {Collections.reverse(iterm);}res.add(new ArrayList(iterm));}return res;}public static void main(String[] args) {Scanner sc new Scanner(System.in);String input sc.nextLine();input input.replace([,);input input.replace(],);String[] parts input.split(,);Integer[] nums new Integer[parts.length];for(int i 0 ; i parts.length ;i){if(!parts[i].equals(null)){nums[i] Integer.parseInt(parts[i]);}else{nums[i] null;}}TreeNode root build(nums);levelTraversal(root);System.out.println(结果为res.toString());}
}