/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int pre=0;
public TreeNode convertBST(TreeNode root) {
dfs(root);
return root;
}
//这里我们逆中序遍历一下
void dfs(TreeNode root){
if(root==null){
return;
}
dfs(root.right);
root.val+=pre;
pre=root.val;
dfs(root.left);
}
}
2022-02-21(把二叉搜索树转换为累加树)
最新推荐文章于 2025-12-18 17:00:31 发布
该博客介绍了一种方法,通过逆中序遍历将二叉搜索树(BST)转换为累加树,使得每个节点的值等于原BST中从该节点到根节点路径上的所有节点值之和。在转换过程中,使用了深度优先搜索(DFS)策略。
286

被折叠的 条评论
为什么被折叠?



