LeetCode Top 100 Liked Questions 538. Convert BST to Greater Tree (Java版; Easy)

mac2025-08-10  7

welcome to my blog

LeetCode Top 100 Liked Questions 538. Convert BST to Greater Tree (Java版; Easy)

题目描述

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

class Solution { public TreeNode convertBST(TreeNode root) { if(root==null){ return root; } //反中序遍历, 迭代版 Stack<TreeNode> s = new Stack<>(); int sum = 0; TreeNode cur = root; while(!s.isEmpty() || cur!=null){ while(cur!=null){ s.push(cur); cur = cur.right; } cur = s.pop(); sum+=cur.val; cur.val = sum; cur = cur.left; } return root; } } class Solution { //反中序遍历的累加和 private int sum = 0; public TreeNode convertBST(TreeNode root) { if(root==null){ return root; } convertBST(root.right); sum += root.val; root.val = sum; convertBST(root.left); return root; } }

class Solution { public TreeNode convertBST(TreeNode root) { core(root, 0); return root; } //因为是搜索二叉树, 所以可以以右根左的顺序遍历, 这样是降序 private int core(TreeNode root, int parentSum){ if(root==null){ return 0; } //right int R = core(root.right, parentSum); //root int tmp = root.val; root.val = root.val + R + parentSum; //left int L = core(root.left, root.val); return L + tmp + R; } }

最开始的错误原因, 估计之后看就看不懂了, 主要是提醒自己得熟练的画图梳理递归逻辑

错误原因:root右子树的考虑了root父节点的信息, 重复了, root右子树应该返回1

第一次做; 考察二叉树遍历; 采用右根左的形式; 涉及到前缀和, 需要很小心; 返回值和直接功能分离

/* DFS; 右根左的形式遍历二叉树, 记录累计和, 将累计和加入当前节点上 */ class Solution { public TreeNode convertBST(TreeNode root) { if(root==null) return null; core(root, 0); return root; } public int core(TreeNode root, int preSum){ if(root==null) return 0; //右; 新条件新递归 int rightRes = core(root.right, preSum); //根; 当前条件 //记录当前节点的原始值 int old = root.val; //更新当前节点的值 root.val = root.val + rightRes + preSum; //左; 新条件新递归 int leftRes = core(root.left, root.val); //核心: 返回的是以root为根的子树的原始值的和 return leftRes + old + rightRes; } }
最新回复(0)