LeetCode(20), Construct Binary Search Tree From Preorder Traversal

Description

Return the root node of a binary search tree that matches the given preordertraversal.

(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)

It’s guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Constraints:

  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 10^8
  • The values of preorder are distinct.

Solution

在递归调用时,需要传入对应根节点的值。当碰到一个新的值时,对比节点值的大小决定是要插入到左节点还是右节点。直接看java code:

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}


public class PreoderToBST {
    private int i = 0;

    public TreeNode bstFromPreorder(int[] A) {
        return bstFromPreorder(A, Integer.MAX_VALUE);
    }

    private TreeNode bstFromPreorder(int[] A, int bound) {
        if (i == A.length || A[i] > bound) return null;
        TreeNode root = new TreeNode(A[i++]);
        root.left = bstFromPreorder(A, root.val);
        root.right = bstFromPreorder(A, bound);
        return root;
    }

    public static void main(String[] args) {
        PreoderToBST ptb = new PreoderToBST();
        int[] A = {8, 5, 1, 7, 10, 12};
        TreeNode root = ptb.bstFromPreorder(A);
        System.out.println("end");
    }
}
  1. 程序运行到某一个节点时,当前节点的值为root.val,其父节点的值为bound
  2. 新插入的是数组中的下一个节点,首先创建这个新节点
  3. 如果新节点的值比当前节点的值小,就将其插入到当前节点的左叶节点中
  4. 如果新节点的值比当前节点的值大,那么当前节点的左叶节点为空,返回一个null值给左叶节点
  5. 把这个新节点插入到右子叶节点中,如果这个数比当前节点的值root.val大,但是小于当前节点的父节点值bound,那么就将其插入到当前节点的右叶节点
  6. 如果这个新节点比当前节点的父节点值bound还要大,说明这个新节点应该在父节点的右子树中。而此时,当前节点的右叶节点应该为null
  7. 完成当前节点的左叶节点和右叶节点赋值后,返回这个节点。

相似的思路,用Python写如下:

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class BST:
    # construct bst from preoder traversal
    i = 0
    def bst_from_preorder(self, A: [int], bound=float('inf')):
        if self.i == len(A) or A[self.i] > bound:
            return None
        root = TreeNode(A[self.i])
        self.i += 1
        root.left = self.bst_from_preorder(A, root.val)
        root.right = self.bst_from_preorder(A, bound)
        return root

    
    def bst_inorder(self, root: TreeNode):
        if root == None:
            return
        self.bst_inorder(root.left)
        print(root.val, ' ', end='')
        self.bst_inorder(root.right)

    def bst_preorder(self, root: TreeNode):
        if root == None:
            return
        print(root.val, ' ', end='')
        self.bst_preorder(root.left)
        self.bst_preorder(root.right)

    def bst_postorder(self, root: TreeNode):
        if root == None:
            return
        self.bst_postorder(root.left)
        self.bst_postorder(root.right)
        print(root.val, ' ', end='')

bst = BST()
bst.root = bst.bst_from_preorder([8, 5, 1, 7, 10, 12])
print('\nbst inorder traversal')
bst.bst_inorder(bst.root)
print('\nbst preorder traversal')
bst.bst_preorder(bst.root)
print('\nbst postorder traversal')
bst.bst_postorder(bst.root)
print()

Output:

bst inorder traversal
1  5  7  8  10  12  
bst preorder traversal
8  5  1  7  10  12  
bst postorder traversal
1  7  5  12  10  8  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值