108. 将有序数组转换为二叉搜索树
思路: 这道题和654最大二叉树有异曲同工之妙。
public class Solution {
public TreeNode SortedArrayToBST(int[] nums) {
int index = nums.Length/2;
TreeNode node = new TreeNode(nums[index]);
if(index > 0)
{
int[] left = new int[index];
for (int i = 0; i < index; i++)
{
left[i] = nums[i];
}
node.left = SortedArrayToBST(left);
}
if (index < nums.Length - 1)
{
int[] right = new int[nums.Length - index-1];
for (int i = 0; i < nums.Length - index - 1; i++)
{
right[i] = nums[index+i+1];
}
node.right = SortedArrayToBST(right);
}
return node;
}
}
538. 把二叉搜索树转换为累加树
思路: 本题和530. 二叉搜索树的最小绝对差,501. 二叉搜索树中的众数 有异曲同工之妙。
public class Solution {
private int pre = Int32.MinValue;
public TreeNode ConvertBST(TreeNode root) {
InOrder(root);
return root;
}
public void InOrder(TreeNode root)
{
if(root == null) return;
InOrder(root.right);
if(pre == Int32.MinValue)
{
pre = root.val;
}
else
{
pre += root.val;
}
root.val = pre;
InOrder(root.left);
}
}