当前位置:网站首页>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;
}
}
边栏推荐
- Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13
- Detailed explanation of common network attacks
- How to enforce parameters in PowerShell- How do I make parameters mandatory in PowerShell?
- The largest matrix (H) in a brush 143 monotone stack 84 histogram
- AcWing 4489. Longest subsequence
- Define a structure fraction to represent a fraction, which is used to represent fractions such as 2/3 and 5/6
- Where is the monitoring page of RDS database?
- C language modifies files by line
- RDS数据库的监测页面在哪看?
- [RT thread] NXP rt10xx device driver framework -- Audio construction and use
猜你喜欢
Take you to API development by hand
IntelliJ 2021.3 short command line when running applications
【RT-Thread】nxp rt10xx 设备驱动框架之--rtc搭建和使用
Internet Hospital his Management Platform source, online Inquiry, appointment Registration Smart Hospital Small program source
kubernetes资源对象介绍及常用命令(四)
1146_ SiCp learning notes_ exponentiation
Tensorboard quick start (pytoch uses tensorboard)
Internet hospital his management platform source code, online consultation, appointment registration smart hospital applet source code
[RT thread] NXP rt10xx device driver framework -- pin construction and use
[RT thread] NXP rt10xx device driver framework -- RTC construction and use
随机推荐
Assignment examination questions of advanced English (III) for the course examination of Fujian Normal University in February 2022
RedHat 6.2 配置 Zabbix
27. Input 3 integers and output them in descending order. Pointer method is required.
Comparison of kotlin collaboration + retro build network request schemes
Applet setting multi account debugging
Play with fancy special effects. This AE super kit is for you
自动渗透测试工具核心功能简述
Visual studio "usually, each socket address (Protocol / network address / port) can only be used once“
Test your trained model
One brush 149 force deduction hot question-10 regular expression matching (H)
PHP online confusion encryption tutorial sharing + basically no solution
【RT-Thread】nxp rt10xx 设备驱动框架之--Audio搭建和使用
[combinatorics] recursive equation (example of solving recursive equation without multiple roots | complete process of solving recursive equation without multiple roots)
【RT-Thread】nxp rt10xx 设备驱动框架之--rtc搭建和使用
Collection of the most beautiful graduation photos in the graduation season, collection of excellent graduation photos
Kotlin learning quick start (7) -- wonderful use of expansion
[combinatorics] recursive equation (solution of linear non-homogeneous recursive equation with constant coefficients | standard form and general solution of recursive equation | proof of general solut
AcWing 3438. Number system conversion
新库上线 | CnOpenData中国观鸟记录数据
Internet Hospital his Management Platform source, online Inquiry, appointment Registration Smart Hospital Small program source