当前位置:网站首页>Leetcode 538 converts binary search tree into cumulative tree -- recursive method and iterative method
Leetcode 538 converts binary search tree into cumulative tree -- recursive method and iterative method
2022-07-03 17:27:00 【Hello, I'm Boger】
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/convert-bst-to-greater-tree
The question :
Give a binary Search for Root node of tree , The node values of the tree are different , Please convert it to an accumulation tree (Greater Sum Tree), Make each node node The new value of is equal to or greater than in the original tree node.val The sum of the values of .
As a reminder , The binary search tree satisfies the following constraints :
The left subtree of a node contains only the key Less than Node key node .
The right subtree of a node contains only the key Greater than Node key node .
Left and right subtrees must also be binary search trees .
Be careful : This topic and 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ identical
Example 1:
Input :[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output :[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:
Input :root = [0,null,1]
Output :[1,null,1]
Example 3:
Input :root = [1,0,2]
Output :[3,3,2]
Example 4:
Input :root = [3,2,4,1]
Output :[7,9,4,10]
Tips :
The number of nodes in the tree is between 0 and 104 Between .
The value of each node is between -104 and 104 Between .
All the values in the tree Different from each other .
The given tree is a binary search tree .
Ideas :
Code Capriccio recorded in 《 Binary tree : Conclusion !》 The summary written in it is very good , I'll post it here :
- It involves the construction of binary tree , Whether ordinary binary tree or binary search tree, there must be a preamble , All nodes are constructed first .
- Find the properties of ordinary binary tree , Generally, it is a post order , It is usually calculated by the return value of recursive function .
- Find the properties of binary search tree , It must be the middle order , Or you'll be blind to order .
Because this problem involves the evaluation of binary search tree attributes , So we use middle order traversal to do , But the middle order traversal of this problem is a special middle order traversal .
In fact, this problem is not difficult , As long as you understand the idea, it is very simple !
Mention binary search tree , Think immediately Using middle order traversal on binary search tree will get an ordered sequence , And what this topic says is accumulation ( Make each node node The new value of is equal to or greater than in the original tree node.val The sum of the values of .), In fact, it is to add the value of each node In this ordered sequence, the sum of all numbers after the corresponding value of the current node .
After understanding this idea , In fact, we traverse the binary search tree in reverse order ( That is, first traverse the right node , Then traverse the intermediate nodes , Finally, traverse the left node ), And this process uses a sum The current value can be superimposed by the variable .
We use iteration and recursion to do this problem respectively , Are to achieve the binary tree in the order of traversal ( Reverse order ).
Recursive method Java Code :
class Solution {
int sum;
private void search(TreeNode node) {
if (node == null) return;
search(node.right);
node.val += sum;
sum = node.val;
search(node.left);
}
public TreeNode convertBST(TreeNode root) {
search(root);
return root;
}
}
Iterative method Java Code :
class Solution {
public TreeNode convertBST(TreeNode root) {
TreeNode cur = root;
int sum = 0;
Deque<TreeNode> deque = new LinkedList<>();
while (cur != null || !deque.isEmpty()) {
if (cur != null) {
deque.push(cur);
cur = cur.right;
} else {
cur = deque.poll();
cur.val += sum;
sum = cur.val;
cur = cur.left;
}
}
return root;
}
}
边栏推荐
- Where is the database account used when running SQL tasks in data warehouse tasks configured
- Free data | new library online | cnopendata complete data of China's insurance intermediary outlets
- Depth first search of graph
- Kubernetes resource object introduction and common commands (4)
- Solution to long waiting time of SSH connection to remote host
- [combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th
- Installation and configuration of network hard disk NFS
- Detailed explanation of common network attacks
- PHP online confusion encryption tutorial sharing + basically no solution
- Cross border e-commerce: advantages of foreign trade enterprises in overseas social media marketing
猜你喜欢

Tensorboard quick start (pytoch uses tensorboard)

Wechat applet for the first time

Play with fancy special effects. This AE super kit is for you

How do large consumer enterprises make digital transformation?

Simple use of unity pen XR grab

Redis: operation commands for list type data

PHP online confusion encryption tutorial sharing + basically no solution
![How to read the source code [debug and observe the source code]](/img/40/a2fca67bcde3c468a739c6990325f4.jpg)
How to read the source code [debug and observe the source code]

Free data | new library online | cnopendata complete data of China's insurance intermediary outlets

Depth first search of graph
随机推荐
RDS数据库的监测页面在哪看?
Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
How to purchase Google colab members in China
[combinatorics] recursive equation (definition of general solution | structure theorem of general solution of recursive equation without multiple roots)
1146_ SiCp learning notes_ exponentiation
Select 3 fcpx plug-ins. Come and see if you like them
企业级自定义表单引擎解决方案(十一)--表单规则引擎1
Apache service suspended asynchronous acceptex failed
Depth first search of graph
vs2013已阻止安装程序,需安装IE10
AcWing 4489. Longest subsequence
Electronic Science and technology 20th autumn "Microcomputer Principle and application" online assignment 2 [standard answer]
Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13
Answer to the homework assessment of advanced English reading (II) of the course examination of Fuzhou Normal University in February 2022
How SVN views modified file records
AcWing 4489. 最长子序列
TensorBoard快速入门(Pytorch使用TensorBoard)
Thread pool: the most common and error prone component of business code
【RT-Thread】nxp rt10xx 设备驱动框架之--Audio搭建和使用
国内如何购买Google Colab会员