二叉搜索树中第k小的元素
思路
- 中序遍历二叉搜索树,得到的是递增有序列表。
代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
search(root, k);
return res;
};
var curr = 0;
var res = 0;
// 中序遍历二叉搜索树
var search = function(root, k){
if(root==null){
return;
}
search(root.left, k);
curr++;
if(curr==k){
res = root.val
return;
}
search(root.right, k);
}
二叉树转累加树
思路
- 右 => 根 => 左,全局变量currSum记录当前累加和。
代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
// 右 => 根 => 左
var currSum = 0;
var convertBST = function(root) {
if(root==null){
return;
}
convertBST(root.right);
currSum += root.val;
root.val = currSum;
convertBST(root.left);
return root;
};