题解 | #从上往下打印二叉树#

从上往下打印二叉树

https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=265&tqId=39234&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=undefined&judgeStatus=3&tags=&title=

层次遍历

/*
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) {
      std::vector<int> res;
      
      if (root == nullptr) {
        return res;
      }
      
      std::queue<TreeNode *> tree;
      tree.push(root);
      
      while (!tree.empty()) {
        int size = tree.size();
        
        for (int i = 0; i < size; ++i) {
          TreeNode *tmp = tree.front();
          tree.pop();
          res.push_back(tmp->val);
          if (tmp->left) {
            tree.push(tmp->left);
          }
          if (tmp->right) {
            tree.push(tmp->right);
          }
        }
      }
      
      return res;
    }
};
全部评论

相关推荐

秋招投简历提醒助手:个人经验是,一般面二十场左右就会进入侃侃而谈阶段。我今年七月末的时候开始的第一次面试,都是很多不会,回复很慢。后面慢慢迭代,到九月中的时候基本上面啥说啥,很放松的状态
远程面试的尴尬瞬间
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务