二叉查找树其他操作

将二叉搜索树转变为排序的双向链表

来源:剑指offer27
思路:想成是中序遍历的变形,可以利用中序遍历的非递归方式不断压栈弹栈,保存前一个节点与其互指。
也可以使用递归方式,每次可以返回已成形链表的最后一个节点,用给节点连接当前节点,再将当前节点的右子树的最小节点连接起来。

public TreeNode last = null;
public TreeNode Convert(TreeNode root){
    if(root == null) return null;
    TreeNode head = root;
    for(; head.left != null; head = head.left);
    ConvertToList(root);
    return head;
}
public void ConvertToList(TreeNode root){
    if(root.left != null) ConvertToList(root.left);
    root.left = last;
    if(last != null) last.right = root;
    last = root;
    if(root.right != null) ConvertToList(root.right);
}

实现二叉查找树的iterator

https://leetcode.com/problems/binary-search-tree-iterator/

/**
* Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root
* node of a BST.
* Calling next() will return the next smallest number in the BST.
* Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of 
* the tree.
**/

思路:非递归中序遍历的实现,内置一个辅助栈,每次从栈顶取得元素,判断时判断栈顶是否为空即可。
由于中序遍历将所有元素遍历一遍,即将所有元素会入栈一次,而每次获取时会弹栈,即所有元素会弹出一次,因此调用n此next()函数的总时间复杂度为O(2n),平均下来为O(2)是常数复杂度的,符合条件

public class BSTIterator {
    Deque<TreeNode> deque = null;
    public BSTIterator(TreeNode root) {
        deque = new ArrayDeque<TreeNode>();
        for(TreeNode head = root; head != null; deque.add(head), head = head.left);
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return deque.isEmpty() == true ? false : true;
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode top = deque.pollLast();
        for(TreeNode head = top.right; head != null; deque.add(head), head = head.left);
        return top.val;
    }
}

f = (最大值+最小值)/2,设计一个算法,找出距离f值最近,大于f值得节点。

public TreeNode getNode(TreeNode root){
    if(root == null) return null;
    int max = 0, min = 0, mid = 0;
    for(TreeNode tmp = root; tmp.right != null; max = tmp.val, tmp = tmp.right);
    for(TreeNode tmp = root; tmp.left != null; min = tmp.val, tmp = tmp.left);
    mid = (max + min)/2;
    TreeNode rs = root, tmp = root;
    while(tmp != null){
        if(tmp.val < mid) tmp = tmp.right;
        else{
            rs = tmp;
            tmp = tmp.left;
        }
    }
    return rs;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值