LeetCode題庫解答與分析——#103. 二叉樹的鋸齒形層次遍歷BinaryTreeZigzagLevelOrderTraversal
阿新 • • 發佈:2019-02-08
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回鋸齒形層次遍歷如下:
[ [3], [20,9], [15,7] ]
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
個人思路:
以二叉樹的層次遍歷的思路為基礎,定義direction作為儲存方向(true代表向右儲存,false代表向左儲存),以滿足鋸齒形儲存的要求,仍然按層次遍歷取得子陣列,每次內迴圈獲得一層的元素,並在每一輪結束後根據direction的布林值進行順序儲存或反向儲存,構成新的子陣列加入總陣列,最終得到鋸齒形層次遍歷陣列。
程式碼(Java):
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { Queue<TreeNode> queue=new LinkedList<TreeNode>(); List<List<Integer>> visited=new LinkedList<List<Integer>>(); int row=0,col=0; Boolean direction=true;//true代表向右,false代表向左 if(root!=null){queue.offer(root);} else{return visited;} while(!queue.isEmpty()){ int level=queue.size(); List<Integer> sub_visited=new LinkedList<Integer>(); Stack<Integer> sub_stack=new Stack<Integer>(); List<Integer> sub_queue=new LinkedList<Integer>(); for(int i=0;i<level;i++){ if(queue.peek().left!=null){queue.offer(queue.peek().left);} if(queue.peek().right!=null){queue.offer(queue.peek().right);} int value=queue.poll().val; sub_stack.push(value); sub_queue.add(value); } if(direction==true){ sub_visited=sub_queue; } else{ while(!sub_stack.isEmpty()){ sub_visited.add(sub_stack.pop()); } } direction=!direction; visited.add(sub_visited); } return visited; } }