码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-103-Binary Tree Zigzag Level Order Traversal

时间:2019-02-03 10:27:16      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:order   turn   traversal   div   null   binary   水平   between   tree   

算法描述:

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

解题思路:与水平访问一样,用队列实现。区别在于加入一个判断,在偶数行反向插入数值就行。

    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> results;
        helper(root, results,0);
        return results;
    }
    
    void helper(TreeNode* root, vector<vector<int>>& results, int level){
        if(root ==nullptr) return;
        if(results.size() <= level){
            vector<int> temp;
            results.push_back(temp);
        }
        if(level%2==0){
            results[level].push_back(root->val);
        }else{
            results[level].insert(results[level].begin(),root->val);
        }

        helper(root->left,results,level+1);
        helper(root->right,results,level+1);

    }

 

LeetCode-103-Binary Tree Zigzag Level Order Traversal

标签:order   turn   traversal   div   null   binary   水平   between   tree   

原文地址:https://www.cnblogs.com/nobodywang/p/10349580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!