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

从上往下打印二叉树

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

相关推荐

点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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