Verify Preorder Sequence in Binary Search Tree

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.

You may assume each number in the sequence is unique.

Follow up:
Could you do it using only constant space complexity?

思路:preorder 生成的数组序列,并不像inorder那么递增,但是也还是有一定规律的,因为preorder的至少是一个BST的序列,所以,BST有性质就是:左<中<右。

也就是说,当前node的值必须比左边的要大,那么我们就维持一个stack,来保存visit当前点的左边最小值,如果后面visit出来的点值比左边还小,那就坏了return false。

说白了,就是为了验证这个树形结构是否是正确的,我们为了维护一个当前点的最小值,那么就要用stack来保存。

算法就是:只要遇见小于当前stack.peek()的点的值,就push进去,如果遇见比peek大的值,那么证明我们遇见了右边的点,那么pop stack直到peek的值比当前值大,同时我们需要更新最小值为pop的值,也就是随着我的点右移,我的最小值也应该随着往右移动,这样就模拟验证了整个tree是不是valid。注意int array也可以for循环,直接for int p就行。不需要用Integer。

public class Solution {
    public boolean verifyPreorder(int[] preorder) {
        if(preorder == null) return false;
        int min = Integer.MIN_VALUE;
        Stack<Integer> stack = new Stack<Integer>();
        for(int p: preorder){
            if(p < min){
                return false;
            } 
            
            while(!stack.isEmpty() && stack.peek() < p){
                min = stack.pop();
            }
            stack.push(p);
        }
        return true;
    }
}

follow up,如果需要用constant space,那就需要把最小值直接修改记录在preorder的array里面,这样就不用stack来记录历史信息。这个很巧妙。这个思想就是把array当stack用,然后把后面遇见的a,放到前面去,然后low的值取完了之后,历史信息就没有用了,所以可以把后面的值放到前面去。

public class Solution {
    public boolean verifyPreorder(int[] preorder) {
        if(preorder == null) return false;
        int min = Integer.MIN_VALUE;
        int i=-1;
        for(int a: preorder){
            if(a<min) return false;
            while(i>=0 && a > preorder[i]){
                min = preorder[i--];
            }
            preorder[++i] = a;
        }
        return true;
    }
}


【Solution】 To convert a binary search tree into a sorted circular doubly linked list, we can use the following steps: 1. Inorder traversal of the binary search tree to get the elements in sorted order. 2. Create a doubly linked list and add the elements from the inorder traversal to it. 3. Make the list circular by connecting the head and tail nodes. 4. Return the head node of the circular doubly linked list. Here's the Python code for the solution: ``` class Node: def __init__(self, val): self.val = val self.prev = None self.next = None def tree_to_doubly_list(root): if not root: return None stack = [] cur = root head = None prev = None while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() if not head: head = cur if prev: prev.right = cur cur.left = prev prev = cur cur = cur.right head.left = prev prev.right = head return head ``` To verify the accuracy of the code, we can use the following test cases: ``` # Test case 1 # Input: [4,2,5,1,3] # Output: # Binary search tree: # 4 # / \ # 2 5 # / \ # 1 3 # Doubly linked list: 1 <-> 2 <-> 3 <-> 4 <-> 5 # Doubly linked list in reverse order: 5 <-> 4 <-> 3 <-> 2 <-> 1 root = Node(4) root.left = Node(2) root.right = Node(5) root.left.left = Node(1) root.left.right = Node(3) head = tree_to_doubly_list(root) print("Binary search tree:") print_tree(root) print("Doubly linked list:") print_list(head) print("Doubly linked list in reverse order:") print_list_reverse(head) # Test case 2 # Input: [2,1,3] # Output: # Binary search tree: # 2 # / \ # 1 3 # Doubly linked list: 1 <-> 2 <-> 3 # Doubly linked list in reverse order: 3 <-> 2 <-> 1 root = Node(2) root.left = Node(1) root.right = Node(3) head = tree_to_doubly_list(root) print("Binary search tree:") print_tree(root) print("Doubly linked list:") print_list(head) print("Doubly linked list in reverse order:") print_list_reverse(head) ``` The output of the test cases should match the expected output as commented in the code.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值