框架
- 把要建树的值一次插入到树中,从根结点开始
- 插入:递归调用插入函数,插入到当前位置看是否空,空就新建,不空就比较,再插入左右子树
- 验证:中序遍历看是否有序即可
python代码
class TreeNode:
def __init__(self,x):
self.val = x
self.left, self.right = None, None
def createBST(nums):
root = None
for num in nums:
root = insert(root, num)
return root
def insert(root, val):
if not root: return TreeNode(val)
if val <= root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def inorder(root):
if not root: return
inorder(root.left)
print(root.val)
inorder(root.right)
if __name__ == '__main__':
root = createBST([5,3,2,3,23,434,3,1,4,7,6])
inorder(root)