今日任务
669. 修剪二叉搜索树
108.将有序数组转换为二叉搜索树
538.把二叉搜索树转换为累加树
669. 修剪二叉搜索树
题目链接:
108.将有序数组转换为二叉搜索树
题目链接: . - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return buildHelper(nums, 0, nums.length - 1);
}
private TreeNode buildHelper(int[] nums, int left, int right){
if (left > right) {return null;}
int mid = left + ((right -left) >> 1);
TreeNode newNode = new TreeNode(nums[mid]);
newNode.left = buildHelper(nums, left, mid - 1);
newNode.right = buildHelper(nums, mid + 1,right);
int t = 0 + 1/2;
System.out.println("the value is " + t);
return newNode;
}
}
538.把二叉搜索树转换为累加树
题目链接: . - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int pre = 0;
public TreeNode convertBST(TreeNode root) {
/*
* 统一迭代法
* */
Stack<TreeNode> stack = new Stack();
if (root == null) {return null;}
stack.add(root);
while (!stack.isEmpty()) {
TreeNode tmpNode = stack.pop();
if (tmpNode != null){
if (tmpNode.left != null) {stack.push(tmpNode.left);}
stack.push(tmpNode);
stack.push(null);
if (tmpNode.right != null) {stack.push(tmpNode.right);}
} else {
tmpNode = stack.pop();
tmpNode.val += pre;
pre = tmpNode.val;
}
}
return root;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int pre = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null) return root;
convertBST(root.right);
root.val += pre;
pre = root.val;
convertBST(root.left);
return root;
}
}