void recoverTree(TreeNode* root) { vector<int> nums; visitTree(root, nums); int n = nums.size(); sort(nums.begin(), nums.end()); coverTree(root, 0, n-1, nums); }
Boolean Btree<T>::getFirstNode(T& x) // // Purpose: visits the root of the B-tree. The function // returns TRUE if the B-tree object has a root. // // Parameters: // // input: x - the index to the data associated with the root of // the B-tree. { Bstruct<T> *buf; if (root != BTREE_NIL) { seekNode = TRUE; clearMarks(root); visitTree(root, nodePtr); buf = new Bstruct<T>; readNode(buf, nodePtr); x = buf->data[visitIndex]; delete buf; } return (root != BTREE_NIL) ? TRUE : FALSE; }
void Btree<T>::visitTree(unsigned rootPtr, unsigned &node) // // Purpose: recursive function used to traverse the B-tree. // // Parameters: // // input: rootPtr - index to the root of the B-tree. // // output: node - the index to the next node visited. // { Bstruct<T> *buf = new Bstruct<T>; unsigned n; readNode(buf, rootPtr); n = buf->marked; // terminate recursive traversal? if (n > buf->count) { delete buf; // all nodes have been visited return; } if (buf->nodeLink[n] != BTREE_NIL) visitTree(buf->nodeLink[n], node); if (seekNode && n < buf->count) { buf->marked++; node = rootPtr; visitIndex = buf->marked; seekNode = FALSE; writeNode(buf, rootPtr); } delete buf; }
Boolean Btree<T>::getNextNode(T& x) // // Purpose: visits the next node in the B-tree. The function // returns TRUE if there was a next node to visit. // // Parameters: // // input: x - the index to the data associated with the visited // node. // { Bstruct<T> *buf; seekNode = TRUE; if (root != BTREE_NIL) { visitTree(root, nodePtr); buf = new Bstruct<T>; readNode(buf, nodePtr); if (!seekNode) x = buf->data[visitIndex]; delete buf; } return (!seekNode) ? TRUE : FALSE; }
void visitTree(TreeNode* root, vector<int>& nums) { if (root == NULL) return; visitTree(root->left, nums); nums.push_back(root->val); visitTree(root->right, nums); }