leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0623.cpp (738B)


      1 class Solution {
      2   public:
      3     TreeNode *addOneRow(TreeNode *root, int val, int depth) const {
      4         if (depth == 1) return new TreeNode(val, root, nullptr);
      5         queue<TreeNode *> q;
      6         q.push(root);
      7         for (int lvl = 2; !q.empty(); lvl++) {
      8             for (int k = q.size(); k > 0; k--) {
      9                 TreeNode *root = q.front();
     10                 q.pop();
     11                 if (root->left) q.push(root->left);
     12                 if (root->right) q.push(root->right);
     13                 if (lvl == depth) {
     14                     root->left = new TreeNode(val, root->left, nullptr);
     15                     root->right = new TreeNode(val, nullptr, root->right);
     16                 }
     17             }
     18         }
     19         return root;
     20     }
     21 };