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

从上往下打印二叉树

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;
    }
};
全部评论

相关推荐

01-12 17:45
门头沟学院 Java
985废物一枚:就是问问你能不能接受北京的房租,hr也知道公司工资不高,大概率是要贴钱的
找实习记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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