关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

云南大王-树

发布时间:2020-04-13 00:00:00
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。 分析:二叉搜索树就是每个节点X,大于其左子树的值,小于其右子树的值,其中序排序是递增的。使用中序遍历,每遍历一个节点,k-1,直到k减到1,即为第K小的节点 /* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function KthNode(pRoot, k) { if (pRoot === null || k === 0) { return null; } // 为了能追踪k,应该把KthNodeCore函数定义在这里面,k应该在KthNodeCore函数外面 function KthNodeCore(pRoot) { let target = null; if (pRoot.left !== null) { target = KthNodeCore(pRoot.left, k); } if (target === null) { if (k === 1) { target = pRoot; } k--; } if (target === null && pRoot.right !== null) { target = KthNodeCore(pRoot.right, k); } return target; } return KthNodeCore(pRoot); }  

/template/Home/Zkeys/PC/Static