A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.node
Write a data structure CBTInserter
that is initialized with a complete binary tree and supports the following operations:函數
CBTInserter(TreeNode root)
initializes the data structure on a given tree with head node root
;CBTInserter.insert(int v)
will insert a TreeNode
into the tree with value node.val = v
so that the tree remains complete, and returns the value of the parent of the inserted TreeNode
;CBTInserter.get_root()
will return the head node of the tree.
Example 1:測試
Input: inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]] Output: [null,1,[1,2]]
Example 2:this
Input: inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]] Output: [null,3,4,[1,2,3,4,5,6,7,8]]
樹的廣度優先搜索(利用隊列實現)+ 徹底二叉樹父節點和子節點的下標索引關係spa
class CBTInserter { TreeNode *root{nullptr}; vector<TreeNode *> nodes; void bfs(TreeNode* root){ queue<TreeNode*> qu; if(root) qu.push(root); while(!qu.empty()){ TreeNode* parent=qu.front(); nodes.push_back(parent); qu.pop(); if(parent->left) qu.push(parent->left); if(parent->right) qu.push(parent->right); } } public: CBTInserter(TreeNode *root) { this->root = root; bfs(root); } int insert(int v) { TreeNode *node = new TreeNode(v); nodes.push_back(node); int sz=nodes.size(); TreeNode* parent=nodes[sz/2-1]; cout<<"parent idx: "<<sz/2-1<<endl; if(sz%2==0) parent->left=node; else parent->right=node; // if(sz==1) return 0; 測試用例沒有考慮構造函數調用爲 CBTInserter(nullptr) 的狀況 return parent->val; } TreeNode *get_root() { return root; } };
去掉queuecode
class CBTInserter { TreeNode *root{nullptr}; vector<TreeNode *> nodes; void bfs(TreeNode* root){ if(root==nullptr) return; nodes.push_back(root); int i=0;//i表示當前父節點的索引 int sz=1;//s表示當前向量nodes的長度 while(i<sz){ TreeNode* parent=nodes[i]; if(parent->left){ nodes.push_back(parent->left); sz+=1; } if(parent->right){ nodes.push_back(parent->right); sz+=1; } i++; } } public: CBTInserter(TreeNode *root) { this->root = root; bfs(root); } int insert(int v) { TreeNode *node = new TreeNode(v); nodes.push_back(node); int sz=nodes.size(); TreeNode* parent=nodes[sz/2-1]; cout<<"parent idx: "<<sz/2-1<<endl; if(sz%2==0) parent->left=node; else parent->right=node; // if(sz==1) return 0; 測試用例沒有考慮構造函數調用爲 CBTInserter(nullptr) 的狀況 return parent->val; } TreeNode *get_root() { return root; } };