码迷,mamicode.com
首页 > 其他好文 > 详细

Convert BST to Greater Tree

时间:2017-09-08 14:41:39      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:垃圾   es2017   保存   []   广搜   nbsp   span   style   nod   

    这道题为简单题

  题目:

    技术分享

  思路:

    1、我的思路:首先利用广搜,保存每个节点值在列表中,然后两个for循环列表,使对应列表中的每个值变为题目要求的值,然后再将广搜的列表与节点值列表对应。

这种方法复杂,时间空间复杂度高,运行时还出现超时

    2、大神的思路:利用递归。其实我最开始也是想用递归,但是没有找到转换的规律,看了大神的解答才明白,

  代码:

    1、我的垃圾代码:

 1 class Solution(object):
 2     def convertBST(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: TreeNode
 6         """
 7         if root:
 8             a = [root]
 9             b = [root.val]
10             c = [root]
11             d = []
12         else: return root        
13         while len(a) > 0:
14             node = a.pop()
15             if node.left:
16                 a.insert(0, node.left)
17                 b.append(node.left.val)
18                 c.append(node.left)
19             if node.right:
20                 a.insert(0, node.right)
21                 b.append(node.right.val)
22                 c.append(node.right)
23             
24         for i in range(len(b)):
25             num = 0
26             for j in range(len(b)):
27                 if b[j] > b[i]: num += b[j]
28             num += b[i]
29             d.append(num)
30         for i in range(len(c)):
31             c[i].val = d[i]
32         return root

    2、大神代码:

 1 class Solution {
 2 public:
 3     TreeNode* convertBST(TreeNode* root) {
 4         if (!root) return NULL;
 5         convertBST(root->right);
 6         root->val += sum;
 7         sum = root->val;
 8         convertBST(root->left);
 9         return root;
10     }
11 
12 private:
13     int sum = 0;
14 };

 

Convert BST to Greater Tree

标签:垃圾   es2017   保存   []   广搜   nbsp   span   style   nod   

原文地址:http://www.cnblogs.com/liuxinzhi/p/7494150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!