美文网首页LintCode解题思路LintCode解题思路
OJ lintcode 二叉树的层次遍历

OJ lintcode 二叉树的层次遍历

作者: DayDayUpppppp | 来源:发表于2017-02-19 09:33 被阅读24次

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)


image.png
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 
 
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
public:
    void handle_levelorder(queue<TreeNode *> &q,vector<vector<int>> &res){
        //如果队列不等于空
        vector<int> vi;
        if(q.empty()==false){
            vector<TreeNode*> vt;
            while(q.empty()==false){
                TreeNode * h=q.front();
                q.pop();

                
                vi.push_back(h->val);
                //res.push_back(vi);

                vt.push_back(h);
            }
            res.push_back(vi);

            for(int i=0;i<vt.size();i++){
                if(vt[i]->left!=NULL){
                    q.push(vt[i]->left);
                }
                if(vt[i]->right!=NULL){
                    q.push(vt[i]->right);
                }
            }
            vt.clear();
            handle_levelorder(q,res);
        }
    }
    vector<vector<int>> levelOrder(TreeNode *root) {
        // write your code here

        vector<vector<int>> res;
        queue<TreeNode *> q;
        if(root==NULL){
            return res;
        }
        else{
            q.push(root);
            handle_levelorder(q,res);
        }

        return res;
    }
};

相关文章

网友评论

    本文标题:OJ lintcode 二叉树的层次遍历

    本文链接:https://www.haomeiwen.com/subject/clzdwttx.html