leetcode--面试题32 - I. 从上到下打印二叉树

面试题32 - I. 从上到下打印二叉树
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

例如:
给定二叉树: [3,9,20,null,null,15,7],

  3
 / \
9  20
  /  \
 15   7

返回:

[3,9,20,15,7]

提示:

节点总数 <= 1000

思路:迭代法–BFS

/**
 * 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:
    vector<int> levelOrder(TreeNode* root) {
        vector<int> ans;
        if (root == NULL){
            return ans;
        }
        queue<TreeNode*> q;
        q.push(root);
        TreeNode* pNode = NULL;
        while (!q.empty()){
            pNode = q.front();
            q.pop();
            ans.push_back(pNode->val);
            if (pNode->left){
                q.push(pNode->left);
            }
            if(pNode->right){
                q.push(pNode->right);
            }
        }
        return ans;
    }
};
/*12ms,14.7MB*/

时间复杂度:O(n)
空间复杂度:O(n)

发布了59 篇原创文章 · 获赞 0 · 访问量 1201

猜你喜欢

转载自blog.csdn.net/u011861832/article/details/104553763
今日推荐