剑指offer-搜索二叉树的中序遍历(改编)-JavaScript实现

1.题目描述:

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

2.上代码:

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
var k =0;
function test(pRoot){
    var temp = new TreeNode(null);
    if(pRoot!==null)
    {
       temp =test(pRoot.left);
        if(temp!==null){
            return temp;
        }
        if(--k==0){
            return pRoot;
        }
        temp =test(pRoot.right);
        if(temp!==null){
            return temp;
        }
    }
    return null;
}
function KthNode(pRoot, k)
{
    // write code here
    this.k = k;
    return test(pRoot);
}

 

猜你喜欢

转载自blog.csdn.net/qq_42099097/article/details/107319905
今日推荐