55 Construct Binary Search Tree from Preorder Traversal

题目

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

(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.)

Example 1:
在这里插入图片描述

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

Note:

1 <= preorder.length <= 100
The values of preorder are distinct.

分析

题意:给定一个前序遍历的数组,通过该数组生成二叉搜索树。

一棵简单的二叉树,有根节点root,有左子树root.left,有右子树root.right
如果遍历序列是1.根 2.root.left 3. root.right(简称根左右),则是priorder,前序遍历(也叫先序遍历);
如果是左根右,则称为中序遍历;
如果是左右根,则称为后序遍历;
区别就在于根在何时遍历。

二叉搜索树:
对于任意一个节点都满足
root.left.val<root.val<root.right.val。

二叉树的遍历生成基本是用递归。
本题难点就在于如何“拐弯”。
如上图,当我们遍历到1的时候,如何拐弯到7上面;
当我们遍历完7之后,如何拐弯到10上面。
不难想到,这个“拐弯”,就是结束当前递归。

如何结束当前递归?
⇒ 如何从左到右?
⇒ 左子树递归终点条件是什么?

结合二叉搜索树的特点:如果当前值比上一个值要大,就需要拐弯了(结束当前递归)

解答

class Solution {
    int i = 0;
    public TreeNode bstFromPreorder(int[] A) {
        return helper(A, Integer.MAX_VALUE);
    }

    public TreeNode helper(int[] A, int change) {
        // i==A.length说明递归结束
        // A[i]是当前值,change是上一个值,如果当前值比上一个值大,说明得拐弯了
        if (i == A.length || A[i] > change) return null;
        TreeNode root = new TreeNode(A[i++]);
        // 左子树递归使用当前值
        root.left = helper(A, root.val);
        // 右子树递归使用拐弯后的值
        root.right = helper(A, change);
        return root;
    }
}
发布了118 篇原创文章 · 获赞 26 · 访问量 8007

猜你喜欢

转载自blog.csdn.net/weixin_43367550/article/details/104997325
今日推荐