538. Convert BST to Greater Tree

来源:互联网 发布:学历 知乎 编辑:程序博客网 时间:2024/06/11 02:41

1.题目
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
5
/ \
2 13

Output: The root of a Greater Tree like this:
18
/ \
20 13

2.分析
树形结构接触多了,在想为什么会有树形结构这种东西- -,不够大自然很神奇,存在即合理,树形结构能很好的解决很多现实问题,在数据库设计与一些搜索算法中树形结构的身影都有见到。只是变体挺多的,毕竟树的类型多- -,但一般我们接触的多的都是二叉排序树,树的定义本身是递归定义,树形结构题一个比较直观的解法就是递归,而我自己以及看了一些人的解法也是采用递归。

3.解题
我的解题:
public class Solution {
public TreeNode convertBST(TreeNode root) {
// 边界处理\
if(root==null){
return null;
}
ArrayListlist = numSum(root);
setNumber(root,list);

    return root;}public void setNumber(TreeNode node,ArrayList<Integer>list){    int numtem = node.val;    if(list!=null&&list.size()>0){        int size = list.size();        for(int i=0;i<size;i++){            if(list.get(i)>numtem){                node.val = node.val+list.get(i);            }        }    }    if(node.left!=null){        setNumber(node.left,list);    }    if(node.right!=null){        setNumber(node.right,list);    }}public ArrayList<Integer> numSum(TreeNode node){    ArrayList<Integer>list = new ArrayList<Integer>();    if(node==null){        return list;    }    Queue<TreeNode>q = new LinkedList<TreeNode>();    q.add(node);    while(!q.isEmpty()){        TreeNode tem = q.poll();        if(tem!=null){            list.add(tem.val);        }        if(tem.left!=null){            q.add(tem.left);        }        if(tem.right!=null){            q.add(tem.right);        }    }    return list;}

}
比较傻的办法- -,就是首先查出所有节点值,然后递归对树形结构中每一个节点比较累加赋值。时间复杂度O(n^2),空间复杂度O(n);

别人的解法:
public class Solution {
int sum = 0;

public TreeNode convertBST(TreeNode root) {    if (root == null) return null;    convertBST(root.right);    root.val += sum;    sum = root.val;    convertBST(root.left);    return root;}

}
这种解法就是采用正规的递归方法,只是递归结束条件与累加要控制好。使用递归一定要清楚递归调用流程与回溯流程,代码是真的很简洁- -。

4.总结
个人发现好像目前的水平与追求没有追求最优解- -,只是看了一些人的解题与自己的对比,查找不足与别人的解题巧妙处。以后不断进步后,达到一定量积累后,应该追求最优解。

原创粉丝点击