农民领袖
- 积分
- 12103
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-7-23
- 最后登录
- 1970-1-1
|
照着我自己的想法写了个code,觉得自己有些地方处理的不是很简洁啊,尤其是关于index和层数的处理部分……求给点建议啊啊啊。
还有,我给的test case有限,基本算法写错了一定要告诉我啊啊啊啊……感谢感谢!
- struct TreeNode {
- int val;
- TreeNode *left, *right;
- TreeNode(int v) {
- val = v;
- left = nullptr;
- right = nullptr;
- }
- };
- void bfsPrint(TreeNode* root) {
- if (root==nullptr) return;
- queue<TreeNode*> Q;
- Q.push(root);
- while (!Q.empty()) {
- int len = Q.size();
- for (int i=0; i<len; i++) {
- TreeNode* cur = Q.front();
- Q.pop();
- cout << cur->val << " ";
- if (cur->left) Q.push(cur->left);
- if (cur->right) Q.push(cur->right);
- }
- cout << endl;
- }
- }
- bool isNodeValid_iterative(TreeNode* root, int id) {
- //not sure these two corner cases are valid, better way?
- if (id<=0 || root==nullptr) return false;
- if (id==1 && root!=nullptr) return true;
-
- // find which layer the id is in
- int h = 1;
- while (id>(1<<h)-1) h++;
- // cout << h << endl;
- while (root!=nullptr && id>1) {
- // on the right bra
- // ((1<<h-1)-1): number of nodes on all preivous layers
- // 1<<h-2: half of number of nodes on this layer
- // cout << id << " " << h << endl;
- if (id - ((1<<h-1)-1) > 1<<h-2) {
- root = root->right;
- id -= 1<<h-1;
- } else {
- root = root->left;
- id -= 1<<h-2;
- }
- h--;
- }
- return root!=nullptr && id==1;
- }
- bool helper_recursive(TreeNode* root, int id, int h) {
- if (root==nullptr) return false;
- if (id==1) return true;
- // cout << id << " " << h << endl;
- if (id - ((1<<h-1)-1) > 1<<h-2)
- return helper_recursive(root->right, id - (1<<h-1), h-1);
- else
- return helper_recursive(root->left, id - (1<<h-2), h-1);
- }
- bool isNodeValid_recursive(TreeNode* root, int id) {
- //not sure these two corner cases are valid, better way?
- if (id<=0 || root==nullptr) return false;
- if (id==1 && root!=nullptr) return true;
-
- // find which layer the id is in
- int h = 1;
- while (id>(1<<h)-1) h++;
- // cout << h << endl;
- return helper_recursive(root, id, h);
- }
- int main() {
- TreeNode* root = new TreeNode(1);
- root->left = new TreeNode(2);
- root->right = new TreeNode(3);
- root->left->left = new TreeNode(4);
- root->left->right = new TreeNode(5);
- root->right->left = new TreeNode(6);
- root->left->left->left = new TreeNode(8);
- root->left->left->right = new TreeNode(9);
- root->left->right->left = new TreeNode(10);
- bfsPrint(root);
- cout << endl;
- cout << "Iterative & Recursive" << endl;
- for (int i=0; i<22; i++) {
- cout << i << ": " << (isNodeValid_iterative(root, i) ? "True" : "False") << endl;
- cout << i << ": " << (isNodeValid_recursive(root, i) ? "True" : "False") << endl;
- }
- return 0;
- }
复制代码 |
|