In Order Successor in Binary Search Tree

前端 未结 17 1834
孤独总比滥情好
孤独总比滥情好 2020-11-27 04:11

Given a node in a BST, how does one find the next higher key?

17条回答
  •  -上瘾入骨i
    2020-11-27 04:50

    Doing this in Java

    TreeNode getSuccessor(TreeNode treeNode) {
        if (treeNode.right != null) {
             return getLeftMostChild(treeNode.right);
        } else {
            TreeNode p = treeNode.parent;
            while (p != null && treeNode == p.right) { // traverse upwards until there is no parent (at the last node of BST and when current treeNode is still the parent's right child
                treeNode = p;
                p = p.parent; // traverse upwards
            }
            return p; // returns the parent node
        }
    }
    
    TreeNode getLeftMostChild(TreeNode treeNode) {
        if (treeNode.left == null) {
            return treeNode;
        } else {
            return getLeftMostChild(treeNode.left);
        }
    }
    

提交回复
热议问题