Kth Smallest Element in a Binary Search Tree - Node.js Data Structure

Node.js examples for Data Structure:Binary Tree

Description

Kth Smallest Element in a Binary Search Tree

Demo Code



/**/*  w w  w.j  a  v a2  s  .c o  m*/
 *
 * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

 Note:
 You may assume k is always valid, 1 ? k ? BST's total elements.

 * */

function BinaryTree(data,left,right){
    this.val=data||null;
    this.left=left||null;
    this.right=right||null;
}

BinaryTree.prototype.insert=function(data){
    var n=new BinaryTree(data,null,null,null);
    if(this.root==null){
        this.root=n;
    }else{
        var current=this.root,
            parent;
        while(true){
            parent=current;
            if(data<current.val){
                current=current.left;
                if(current==null){
                    parent.left=n;
                    break;
                }
            }else{
                current=current.right;
                if(current==null){
                    parent.right=n;
                    break;
                }
            }
        }
    }
}
function findKNum(root,k){
    var myStack=[];
    var node=root;
    var i=0;
    while(node||myStack){
        while(node){
            myStack.push(node);
            node=node.left;
        }
        node=myStack.pop();
        i++;
        if(i==k){
            return node.val;
        }
        node=node.right;
    }
}


var nums=new BinaryTree();
nums.insert(23)
nums.insert(45)
nums.insert(16)
nums.insert(37)
nums.insert(3)
nums.insert(99)
nums.insert(22)

console.log(nums.root);
console.log(findKNum(nums.root,3));

Related Tutorials