diff --git a/606-20231208-pass/main.cpp b/606-20231208-pass/main.cpp new file mode 100644 index 0000000..c177011 --- /dev/null +++ b/606-20231208-pass/main.cpp @@ -0,0 +1,94 @@ +#include +using namespace std; +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; +void create(int * val, int cnt, TreeNode *cur,int idx){ + int left_idx = (idx + 1) * 2 - 1; + int right_idx = (idx + 1) * 2 ; + if(left_idx >= cnt && right_idx >= cnt) { + cur->left = nullptr; + cur->right = nullptr; + return; + } + if(val[left_idx] == -1 || left_idx >= cnt){ + cur -> left = nullptr; + }else{ + TreeNode * left_child = new TreeNode(val[left_idx]); + cur->left = left_child; + create(val,cnt,left_child,left_idx); + } + if(val[right_idx] == -1 || right_idx >= cnt){ + cur -> right = nullptr; + }else{ + TreeNode * right_child = new TreeNode(val[right_idx]); + cur->right = right_child; + create(val, cnt, right_child, right_idx); + } + return; +} +void traverse(TreeNode* node){ + cout<val<<' '; + if(node->left != nullptr){ + traverse(node->left); + } + if(node->right != nullptr){ + traverse(node->right); + } + return; +} +TreeNode* createTree(int * val, int cnt){ + TreeNode * root = new TreeNode(val[0]); + cout<<"create a tree"<val)); + if(node -> left == nullptr && node -> right == nullptr) return str; + if(node -> left == nullptr){ + str.push_back('('); + str.push_back(')'); + }else{ + str.push_back('('); + traverse(node->left, str); + str.push_back(')'); + } + if(node -> right == nullptr){ + return str; + }else{ + str.push_back('('); + traverse(node->right, str); + str.push_back(')'); + return str; + } + + } + string tree2str(TreeNode * root){ + string rlt = ""; + return traverse(root,rlt); + } + +}; + +int main(){ + Solution sol; + int ex1_val[4] = {1,2,3,4}; + TreeNode * ex1 = createTree(ex1_val,4); + cout<