本文主要是介绍【LeetCode刷题-树】-- 103.二叉树的锯齿形层序遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
103.二叉树的锯齿形层序遍历
方法:广度优先搜索
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<List<Integer>> zigzagLevelOrder(TreeNode root) {//利用广度优先搜索List<List<Integer>> ans = new LinkedList<List<Integer>>();if(root == null){return ans;}Queue<TreeNode> queue = new LinkedList<>(); //定义一个队列queue.offer(root);boolean isLeft = true;while(!queue.isEmpty()){Deque<Integer> levelList = new LinkedList<>();int size = queue.size();for(int i = 0 ;i < size;i++){TreeNode curNode = queue.poll();if(isLeft){levelList.offerLast(curNode.val);}else{levelList.offerFirst(curNode.val);}if(curNode.left!=null){queue.offer(curNode.left);}if(curNode.right!=null){queue.offer(curNode.right);}}ans.add(new LinkedList<Integer>(levelList));isLeft = !isLeft;}return ans;}}
这篇关于【LeetCode刷题-树】-- 103.二叉树的锯齿形层序遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!