diff --git a/ConstructBTFromInorderAndPostorder.cpp b/ConstructBTFromInorderAndPostorder.cpp new file mode 100644 index 00000000..82e0edd5 --- /dev/null +++ b/ConstructBTFromInorderAndPostorder.cpp @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * 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) {} + * }; + */ +class Solution { +public: + unordered_map um; + int postIndex; + TreeNode* helper(vector& postorder, int left, int right) { + if (left > right) { + return nullptr; + } + + TreeNode *root = new TreeNode(postorder[postIndex]); + postIndex--; + + int rootIndex = um[root->val]; + + root->right = helper(postorder, rootIndex+1, right); + root->left = helper(postorder, left, rootIndex-1); + + return root; + } + + TreeNode* buildTree(vector& inorder, vector& postorder) { + for (int i=0;ipostIndex = inorder.size()-1; + + int left = 0; + int right = inorder.size()-1; + return helper(postorder, left, right); + } +}; diff --git a/SumRootToLeaf.cpp b/SumRootToLeaf.cpp new file mode 100644 index 00000000..d799de37 --- /dev/null +++ b/SumRootToLeaf.cpp @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * 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) {} + * }; + */ +class Solution { +public: + vector answer; + int sumNumbers(TreeNode* root) { + helper(root, ""); + int result=0; + for (string s:answer) { + result+= std::stoi(s); + } + return result; + } + + void helper(TreeNode* root, string currSum) { + if (root == NULL) return; + + if (root->left == NULL && root->right == NULL) { + currSum+=std::to_string(root->val); + answer.push_back(currSum); + } + currSum+=std::to_string(root->val); + + helper(root->left, currSum); + helper(root->right, currSum); + } +};