zl程序教程

您现在的位置是:首页 >  后端

当前栏目

LintCode 二叉树的层次遍历

二叉树遍历 层次 lintcode
2023-09-14 09:10:06 时间

中等 二叉树的层次遍历

33%
通过

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

您在真实的面试中是否遇到过这个题? 
Yes
例子

给出一棵二叉树 {3,9,20,#,#,15,7},

    3

   / \

  9  20

    /  \

   15   7

返回它的层次遍历为:

[

  [3],

  [9,20],

  [15,7]

]

挑战

仅仅使用一个队列去实现它

仅仅用了一个队列,用到了两个计数器,一个记录这一层全然二叉树应该有的节点,还有一个记录这一层缺失的节点


/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode *root) {
        // write your code here
        vector<vector<int>> res;
        if(root == nullptr) {
            return res;
        }
        vector<int> temp;
        queue<TreeNode*> q;
        q.push(root);
        int i = 1;// points every level
        int j = 0;// lost point every level
        while(!q.empty()) {
            TreeNode *p = q.front();
            q.pop();
            if (p==nullptr) {
                ++j;
            }
            else {
               temp.push_back(p->val);
                q.push(p->left);
                q.push(p->right);
            }
            if (i == (temp.size() + j) && temp.size()!=0) {
                res.push_back(temp);
                temp.clear();
                i*=2;
                j*=2;
            }
        }
        return res;
    }
};