展平二叉搜索树:
java版本:
class Solution {
List<Integer> list=new ArrayList<Integer>();
public TreeNode increasingBST(TreeNode root) {
// 二叉树遍历
DFS(root);
TreeNode res=new TreeNode(list.get(0));
TreeNode node=res;
for(int i=1;i<list.size();i++){
TreeNode temp=new TreeNode();
temp.val=list.get(i);
node.right=temp;
node=node.right;
}
return res;
}
public void DFS(TreeNode root){
if(root==null){
return ;
}
DFS(root.left);
list.add(root.val);
DFS(root.right);
}
}
二叉搜索树所有大于等于节点的和。
class Solution {
int count=0;
public TreeNode convertBST(TreeNode root) {
// 存起来排个序
// 统计所有值之和
//前两句的思路是错的
// 直接遍历右边的统计值就行了
TreeNode node=root;
DFS(node);
return node;
}
public void DFS(TreeNode root){
if(root==null){
return ;
}
DFS(root.right);
count+=root.val;
root.val=count;
DFS(root.left);
}
}
网友评论