Created
February 21, 2025 15:15
-
-
Save SuryaPratapK/56151d15507a3973ac8e6b46e1004f1a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 { | |
int pre_idx=0; | |
int post_idx=0; | |
public: | |
TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) { | |
TreeNode* curr = new TreeNode(preorder[pre_idx]); | |
pre_idx++; | |
if(curr->val != postorder[post_idx]) | |
curr->left = constructFromPrePost(preorder,postorder); | |
if(curr->val != postorder[post_idx]) | |
curr->right = constructFromPrePost(preorder,postorder); | |
post_idx++; | |
return curr; | |
} | |
}; | |
/* | |
//JAVA | |
class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { val = x; } | |
} | |
class Solution { | |
private int preIdx = 0; | |
private int postIdx = 0; | |
public TreeNode constructFromPrePost(int[] preorder, int[] postorder) { | |
TreeNode curr = new TreeNode(preorder[preIdx]); | |
preIdx++; | |
if (curr.val != postorder[postIdx]) { | |
curr.left = constructFromPrePost(preorder, postorder); | |
} | |
if (curr.val != postorder[postIdx]) { | |
curr.right = constructFromPrePost(preorder, postorder); | |
} | |
postIdx++; | |
return curr; | |
} | |
} | |
#Python | |
class TreeNode: | |
def __init__(self, val=0, left=None, right=None): | |
self.val = val | |
self.left = left | |
self.right = right | |
class Solution: | |
def __init__(self): | |
self.pre_idx = 0 | |
self.post_idx = 0 | |
def constructFromPrePost(self, preorder, postorder): | |
curr = TreeNode(preorder[self.pre_idx]) | |
self.pre_idx += 1 | |
if curr.val != postorder[self.post_idx]: | |
curr.left = self.constructFromPrePost(preorder, postorder) | |
if curr.val != postorder[self.post_idx]: | |
curr.right = self.constructFromPrePost(preorder, postorder) | |
self.post_idx += 1 | |
return curr | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment