1. 程式人生 > 實用技巧 >從上到下列印二叉樹 III

從上到下列印二叉樹 III

題解:層次遍歷的基礎上加個計數器,偶數層得到的結果反轉一下

/**
 * 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>> levelOrder(TreeNode root) {
if(root == null) return new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    Queue<TreeNode> q = new LinkedList<>();
    int cnt = 0;
    q.add(root);
    while(true){
          List<Integer> list = new ArrayList<>();//定義到外面之後用clear會出錯
          int size = q.size();
          cnt++;
          for(int i=0;i<size;i++){
            TreeNode t = q.poll();
            list.add(t.val); 
            if(t.left != null){
                q.add(t.left);
            }
            if(t.right != null){
                q.add(t.right);
            }
      }
      if(cnt % 2 == 0){
          Collections.reverse(list);
      } 
      res.add(list);  
      if(q.size() == 0) break;  
     
    }
    return res;
    }
}