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

[LeetCode] Binary Tree Level Order Traversal

时间:2014-07-26 14:03:16      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   div   ar   

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,#,#,15,7},

    3
   /   9  20
    /     15   7

 

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    queue<TreeNode*> q; //存放当前层的结点
    
    vector<vector<int> >res;//存放最终的结果

    vector<vector<int> > levelOrder(TreeNode *root) {
        
        if(root==NULL)
            return this->res;
        TreeNode *p = root;
        q.push(p);
        
        fun();
        return res;
    }
private:
    void fun()
    {
        if(this->q.empty())
            return;
        TreeNode *pte;
        queue<TreeNode*> qnext;//存放下一层的结点
        vector<int> te;
        while(!this->q.empty() )
        {
               pte = this->q.front();
               this->q.pop();
               te.push_back(pte->val);
               if(pte->left!=NULL)
               {
                   qnext.push(pte->left);
               }
               if(pte->right != NULL)
               {
                   qnext.push(pte->right);
               }
        }
        res.push_back(te);
        this->q = qnext;
        fun();    
    }
};

思路:用queue存放本层所有的结点,把本层处理完清空queue再存放下一层所有的结点。

[LeetCode] Binary Tree Level Order Traversal,布布扣,bubuko.com

[LeetCode] Binary Tree Level Order Traversal

标签:des   style   blog   color   io   for   div   ar   

原文地址:http://www.cnblogs.com/Xylophone/p/3869732.html

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