剑指offer-从上到下打印二叉树(C++)

1、题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

2、解题思路

该问题本质为二叉树的层序遍历,使用队列实现

代码如下:

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        vector<int> result;
        if(root == nullptr)
            return result;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            result.push_back(q.front()->val);
            if(q.front()->left != nullptr)
                q.push(q.front()->left);
            if(q.front()->right != nullptr)
                q.push(q.front()->right);
            q.pop();
        }
        return result;
    }
};
原创文章 62 获赞 133 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43142797/article/details/105495665