Skip to content

Commit 1404f02

Browse files
authored
Merge pull request #888 from NAVJOT-786/main
added leetcode problem 106 solution
2 parents da7a470 + e9826e1 commit 1404f02

File tree

1 file changed

+194
-0
lines changed

1 file changed

+194
-0
lines changed
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
---
2+
id: Construct-Binary-Tree-from-Inorder-and-postorder-Traversal
3+
title: Construct Binary Tree from Inorder and Postorder Traversal
4+
sidebar_label: 0106-Construct-Binary-Tree-from-Inorder-and-postorder-Traversal
5+
tags:
6+
- Array
7+
- Hash Tabel
8+
- Divide and Conquer
9+
- Tree
10+
- Binary Tree
11+
description: "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
12+
13+
"
14+
---
15+
16+
17+
### Problem Description
18+
19+
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
20+
21+
22+
### Examples
23+
24+
#### Example 1
25+
26+
- **Input:** `inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]`
27+
- **Output:** `[3,9,20,null,null,15,7]`
28+
29+
#### Example 2
30+
31+
- **Input:** `inorder = [-1], postorder=[-1]`
32+
- **Output:** `[-1]`
33+
34+
### Constraints
35+
36+
- $1 \leq \text{inorder.length} \leq 3000$
37+
- $\text{postorder.length} == \text{inorder.length}$
38+
- $-3000 \leq \text{inorder}[i], \text{postorder}[i] \leq 3000$
39+
- postorder and inorder consist of unique values.
40+
- Each value of postorder also appears in inorder.
41+
- postorder is guaranteed to be the postorder traversal of the tree.
42+
- inorder is guaranteed to be the inorder traversal of the tree.
43+
44+
### Solution Code
45+
46+
#### Python
47+
48+
```python
49+
class Solution:
50+
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
51+
n=len(inorder)
52+
poststart=instart=0
53+
postend=inend=n-1
54+
d={}
55+
for i in range(n):
56+
d[inorder[i]]=i
57+
return self.constructTree(postorder,poststart,postend,inorder,instart,inend,d)
58+
59+
def constructTree(self,postorder,poststart,postend,inorder,instart,inend,d):
60+
if poststart>postend or instart>inend:
61+
return None
62+
root=TreeNode(postorder[postend])
63+
elem=d[root.val]
64+
nelem=elem-instart
65+
root.left=self.constructTree(postorder,poststart,poststart+nelem-1,inorder,instart,elem-1,d)
66+
root.right=self.constructTree(postorder,poststart+nelem,postend-1,inorder,elem+1,inend,d)
67+
return root
68+
```
69+
70+
#### Java
71+
72+
```java
73+
class Solution
74+
{
75+
public TreeNode buildTree(int[] inorder, int[] postorder) {
76+
// If either of the input arrays are empty, the tree is empty, so return null
77+
if (inorder.length == 0 || postorder.length == 0) return null;
78+
79+
// Initialize indices to the last elements of the inorder and postorder traversals
80+
int ip = inorder.length - 1;
81+
int pp = postorder.length - 1;
82+
83+
// Create an empty stack to help us build the binary tree
84+
Stack<TreeNode> stack = new Stack<TreeNode>();
85+
// Initialize prev to null since we haven't processed any nodes yet
86+
TreeNode prev = null;
87+
// Create the root node using the last element in the postorder traversal
88+
TreeNode root = new TreeNode(postorder[pp]);
89+
// Push the root onto the stack and move to the next element in the postorder traversal
90+
stack.push(root);
91+
pp--;
92+
93+
// Process the rest of the nodes in the postorder traversal
94+
while (pp >= 0) {
95+
// While the stack is not empty and the top of the stack is the current inorder element
96+
while (!stack.isEmpty() && stack.peek().val == inorder[ip]) {
97+
// The top of the stack is the parent of the current node, so pop it off the stack and update prev
98+
prev = stack.pop();
99+
ip--;
100+
}
101+
// Create a new node for the current postorder element
102+
TreeNode newNode = new TreeNode(postorder[pp]);
103+
// If prev is not null, the parent of the current node is prev, so attach the node as the left child of prev
104+
if (prev != null) {
105+
prev.left = newNode;
106+
// If prev is null, the parent of the current node is the current top of the stack, so attach the node as the right child of the current top of the stack
107+
} else if (!stack.isEmpty()) {
108+
TreeNode currTop = stack.peek();
109+
currTop.right = newNode;
110+
}
111+
// Push the new node onto the stack, reset prev to null, and move to the next element in the postorder traversal
112+
stack.push(newNode);
113+
prev = null;
114+
pp--;
115+
}
116+
117+
// Return the root of the binary tree
118+
return root;
119+
}
120+
}
121+
```
122+
123+
#### C++
124+
125+
```cpp
126+
class Solution {
127+
public:
128+
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
129+
// If either of the input vectors are empty, the tree is empty, so return null
130+
if (inorder.size() == 0 || postorder.size() == 0) return nullptr;
131+
132+
// Initialize indices to the last elements of the inorder and postorder traversals
133+
int ip = inorder.size() - 1;
134+
int pp = postorder.size() - 1;
135+
136+
// Create an empty stack to help us build the binary tree
137+
stack<TreeNode*> st;
138+
// Initialize prev to null since we haven't processed any nodes yet
139+
TreeNode* prev = nullptr;
140+
// Create the root node using the last element in the postorder traversal
141+
TreeNode* root = new TreeNode(postorder[pp]);
142+
// Push the root onto the stack and move to the next element in the postorder traversal
143+
st.push(root);
144+
pp--;
145+
146+
// Process the rest of the nodes in the postorder traversal
147+
while (pp >= 0) {
148+
// While the stack is not empty and the top of the stack is the current inorder element
149+
while (!st.empty() && st.top()->val == inorder[ip]) {
150+
// The top of the stack is the parent of the current node, so pop it off the stack and update prev
151+
prev = st.top();
152+
st.pop();
153+
ip--;
154+
}
155+
// Create a new node for the current postorder element
156+
TreeNode* newNode = new TreeNode(postorder[pp]);
157+
// If prev is not null, the parent of the current node is prev, so attach the node as the left child of prev
158+
if (prev != nullptr) {
159+
prev->left = newNode;
160+
// If prev is null, the parent of the current node is the current top of the stack, so attach the node as the right child of the current top of the stack
161+
} else if (!st.empty()) {
162+
TreeNode* currTop = st.top();
163+
currTop->right = newNode;
164+
}
165+
// Push the new node onto the stack, reset prev to null, and move to the next element in the postorder traversal
166+
st.push(newNode);
167+
prev = nullptr;
168+
pp--;
169+
}
170+
171+
// Return the root of the binary tree
172+
return root;
173+
}
174+
};
175+
```
176+
#### Javascript
177+
178+
```javascript
179+
var buildTree = function(inorder, postorder) {
180+
if (inorder.length == 0 || postorder.length == 0) {
181+
return null;
182+
}
183+
var rootVal = postorder[postorder.length - 1];
184+
var root = new TreeNode(rootVal);
185+
var rootIndex = inorder.indexOf(rootVal);
186+
var leftInorder = inorder.slice(0, rootIndex);
187+
var rightInorder = inorder.slice(rootIndex + 1);
188+
var leftPostorder = postorder.slice(0, leftInorder.length);
189+
var rightPostorder = postorder.slice(leftInorder.length, postorder.length - 1);
190+
root.left = buildTree(leftInorder, leftPostorder);
191+
root.right = buildTree(rightInorder, rightPostorder);
192+
return root;
193+
};
194+
```

0 commit comments

Comments
 (0)