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

LeetCode-102-Binary Tree Level Order Traversal

时间:2019-02-03 10:40:28      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:null   nbsp   return   tree   des   span   evel   ptr   tco   

算法描述:

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

 

return its level order traversal as:

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

解题思路:二叉树水平序列访问,用队列辅助。

    vector<vector<int>> levelOrder(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);
        }
        
        results[level].push_back(root->val);
        helper(root->left, results,level+1);
        helper(root->right,results,level+1);
    }

 

LeetCode-102-Binary Tree Level Order Traversal

标签:null   nbsp   return   tree   des   span   evel   ptr   tco   

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

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