題意:給定一個二叉搜索樹的現(xiàn)需遍歷膏燃,重構二叉搜索樹
思路:先跟遍歷數(shù)組削樊,每次查看當前遍歷到的節(jié)點是否在max和min之內滥搭,如果不在酸纲,返回null,如果在瑟匆,取當前節(jié)點為root闽坡,找到其左右子樹,返回但前節(jié)點
思想:樹的先跟遍歷
復雜度:時間O(n)愁溜,空間O(n)
class Solution {
public TreeNode bstFromPreorder(int[] preorder) {
int len = preorder.length;
if(len == 0)
return null;
return build(preorder, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
int index = 0;
TreeNode build(int[] preorder, int max, int min) {
if(index == preorder.length)
return null;
int temp = preorder[index];
if(temp > max || temp < min)
return null;
TreeNode cur = new TreeNode(preorder[index++]);
cur.left = build(preorder, temp, min);
cur.right = build(preorder, max, temp);
return cur;
}
}