Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codetalks-new/d807267c3264bcf15209 to your computer and use it in GitHub Desktop.
Save codetalks-new/d807267c3264bcf15209 to your computer and use it in GitHub Desktop.
Build Binary Tree with Preorder and Inorder
func buildTreeWithPreorder(preorder:[Int],andInorder inorder:[Int]) -> TreeNode?{
if preorder.isEmpty || inorder.isEmpty{
return nil
}
var branchList = [TreeNode]()
let root = TreeNode(val: 0)
branchList.append(root)
var preorderArray = [[Int]]()
var inorderArray = [[Int]]()
preorderArray.append(preorder)
inorderArray.append(inorder)
while (!preorderArray.isEmpty){
var currentPreorder = preorderArray.removeAtIndex(0)
var currentInorder = inorderArray.removeAtIndex(0)
var currentBranch = branchList.removeAtIndex(0)
var branchNum = currentPreorder.removeAtIndex(0)
currentBranch.val = branchNum
var leftInorder = [Int]()
var rightInorder = [Int]()
var toLeft = true
for num in currentInorder{
if num == branchNum{
toLeft = false
}else{
if toLeft{
leftInorder.append(num)
}else{
rightInorder.append(num)
}
}
}
// 划分左右分支的前序节点出来
var leftPreorder = [Int]()
var rightPreorder = [Int]()
for num in currentPreorder{
if leftInorder.contains(num){
leftPreorder.append(num)
}else{
rightPreorder.append(num)
}
}
if !leftPreorder.isEmpty{
let left = TreeNode(val: 0)
currentBranch.left = left
branchList.append(left)
preorderArray.append(leftPreorder)
inorderArray.append(leftInorder)
}
if !rightPreorder.isEmpty{
let right = TreeNode(val: 0)
currentBranch.right = right
branchList.append(right)
preorderArray.append(rightPreorder)
inorderArray.append(rightInorder)
}
}
return root
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment