Binary Tree Level Order Traversal - LeetCode

Posted 真子集

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Tree Level Order Traversal - LeetCode相关的知识,希望对你有一定的参考价值。

题目链接

Binary Tree Level Order Traversal - LeetCode

注意点

  • 不要访问空结点

解法

解法一:递归,level表示深度,如果当前ret.size()等于深度,就说明到了一个新的深度。用level访问不同的深度。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    typedef vector<vector<int>> v;
    typedef TreeNode* node;
    void bfs(int level,node n,v& ret)
    {
        if(ret.size() == level) ret.push_back({});
        ret[level].push_back(n->val);
        if(n->left) bfs(level+1,n->left,ret);
        if(n->right) bfs(level+1,n->right,ret);
    }
    vector<vector<int>> levelOrder(TreeNode* root) {
        v ret;
        if(!root) return ret;
        queue<node> q;
        q.push(root);
        bfs(0,root,ret);
        return ret;
    }
};

技术图片

解法二:非递归,queue里面存放的是每一层的节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    typedef vector<vector<int>> v;
    typedef TreeNode* node;
    vector<vector<int>> levelOrder(TreeNode* root) {
        v ret;
        if(!root) return ret;
        queue<node> q;
        q.push(root);
        while(!q.empty())
        {
            vector<int> aLevel;
            for(int i = q.size();i > 0;--i)
            {
                node n = q.front();
                q.pop();
                aLevel.push_back(n->val);
                if(n->left) q.push(n->left);
                if(n->right) q.push(n->right);
            }
            ret.push_back(aLevel);
        }
        return ret;
    }
};

技术图片

小结

以上是关于Binary Tree Level Order Traversal - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

102. Binary Tree Level Order Traversal

LeetCode102. Binary Tree Level Order Traversal

Leetcode 103. Binary Tree Zigzag Level Order Traversal

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

Binary Tree Level Order Traversal II

107. Binary Tree Level Order Traversal II