Created
July 2, 2015 05:29
-
-
Save codetalks-new/d807267c3264bcf15209 to your computer and use it in GitHub Desktop.
Build Binary Tree with Preorder and Inorder
This file contains hidden or 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
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