Complete Trees-2#1570
Conversation
|
Strengths:
Areas for improvement:
Revised Solution Suggestion: class Solution {
func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? {
var inMap = [Int: Int]()
for (index, value) in inorder.enumerated() {
inMap[value] = index
}
var postIndex = postorder.count - 1
return buildTreeHelper(postorder, &postIndex, inMap, 0, inorder.count - 1)
}
private func buildTreeHelper(_ postorder: [Int], _ index: inout Int, _ inMap: [Int: Int], _ inStart: Int, _ inEnd: Int) -> TreeNode? {
if inStart > inEnd { return nil }
let rootVal = postorder[index]
index -= 1
let root = TreeNode(rootVal)
let rootIndex = inMap[rootVal]!
root.right = buildTreeHelper(postorder, &index, inMap, rootIndex + 1, inEnd)
root.left = buildTreeHelper(postorder, &index, inMap, inStart, rootIndex - 1)
return root
}
} |
|
Your solution is on the right track and demonstrates a good understanding of the problem. You correctly used a hash map to store inorder indices for efficient root location, and you correctly traversed the postorder array from the end to the beginning. The recursion order (right subtree first, then left) is correct for postorder traversal. However, there are a few issues to address:
To fix the TreeNode initialization, change: let root = TreeNode(val: rootVal, left: nil, right: nil)to: let root = TreeNode(rootVal)Alternatively, if you want to explicitly set left and right to nil, you can use: let root = TreeNode(rootVal, nil, nil)But the first option is simpler. Here is a revised version of your solution without the stateful variable (using a nested function): class Solution {
func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? {
var inMap = [Int: Int]()
for (index, value) in inorder.enumerated() {
inMap[value] = index
}
var postOrderIdx = postorder.count - 1
func constructTree(_ inStart: Int, _ inEnd: Int) -> TreeNode? {
if inStart > inEnd { return nil }
let rootVal = postorder[postOrderIdx]
guard let rootIdx = inMap[rootVal] else { return nil }
postOrderIdx -= 1
let root = TreeNode(rootVal)
root.right = constructTree(rootIdx + 1, inEnd)
root.left = constructTree(inStart, rootIdx - 1)
return root
}
return constructTree(0, inorder.count - 1)
}
}This avoids the class-level variable and uses a nested function to capture Overall, your solution is almost correct but for the compilation error. With that fixed, it would work. |
Problem1 (https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)
Problem2 (https://leetcode.com/problems/sum-root-to-leaf-numbers/)