[Lintcode]Binary Tree Zigzag Level Order Traversal

來源:互聯網
上載者:User

標籤:

Binary Tree Zigzag Level Order Traversal

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).

Example

Given binary tree {3,9,20,#,#,15,7},

    3   /   9  20    /     15   7

 

return its zigzag level order traversal as:

[  [3],  [20,9],  [15,7]]

SOLUTION :

這題跟level order的模版都是一樣的,用queue進行BFS,只不過中間要加一些約束條件,調整level list裡面結果的順序。一般來說碰到類似奇偶迴圈的約束條件,就判斷一下(n % 2 == 0)。很簡單的小技巧,記住就好。 

具體看代碼,備忘調整位置:

public class Solution {    /**     * @param root: The root of binary tree.     * @return: A list of lists of integer include      *          the zigzag level order traversal of its nodes‘ values      */    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();        if (root == null){            return result;        }        Queue<TreeNode> queue = new LinkedList<TreeNode>();        queue.offer(root);        int n = 0;// 增加進行判斷的參數        while (!queue.isEmpty()){            ArrayList<Integer> list = new ArrayList<Integer>();            int size = queue.size();            for (int i = 0; i < size; i++){                TreeNode cur = queue.remove();                //這裡進行list.add的約束                if (n % 2 == 0){                    list.add(cur.val);                } else {                    list.add(0, cur.val);                }                if (cur.left != null){                    queue.offer(cur.left);                }                if (cur.right != null){                    queue.offer(cur.right);                }            }            n++;// 以及這裡            result.add(list);        }        return result;    }}    

  

[Lintcode]Binary Tree Zigzag Level Order Traversal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.