LintCode 71. Binary Tree Zigzag Level Order Traversal

原題

LintCode 71. Binary Tree Zigzag Level Order Traversal

Description

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]
]

代碼

class Solution {
public:
    /*
    * @param root: A Tree
    * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
    */
    vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
        // write your code here
        helper(root, 0);
        return ans;
    }
private:
    vector<vector<int>> ans;
    void helper(TreeNode * root, int depth) {
        if (root == NULL) return;
        if (ans.size() < depth + 1) {
            ans.push_back(vector<int>());
        }
        if (depth % 2) {
            ans[depth].insert(ans[depth].begin(), root->val);
        } else {
            ans[depth].push_back(root->val);
        }
        helper(root->left, depth + 1);
        helper(root->right, depth + 1);
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容