0919.cpp (797B)
1 class CBTInserter { 2 TreeNode *root = nullptr; 3 queue<TreeNode *> q; 4 5 public: 6 CBTInserter(TreeNode *root) : root(root), q({root}) {} 7 TreeNode *get_root() { return root; } 8 9 int insert(int val) { 10 TreeNode *node = new TreeNode(val); 11 while (!q.empty()) { 12 TreeNode *root = q.front(); 13 if (root->left) 14 q.push(root->left); 15 else { 16 root->left = node; 17 q.push(root->left); 18 return root->val; 19 } 20 21 q.pop(); 22 23 if (root->right) 24 q.push(root->right); 25 else { 26 root->right = node; 27 q.push(root->right); 28 return root->val; 29 } 30 } 31 32 return -1; 33 } 34 };