/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int preSum = 0; // 共享单元 public TreeNode convertBST(TreeNode root) { if(root == null) return null; midOrder(root); return root; } // 这就是个中序遍历 public void midOrder(TreeNode root){ if(root == null) return ; midOrder(root.right); root.val = root.val + preSum; preSum = root.val; midOrder(root.left); } } /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: int preSum = 0; public: TreeNode* convertBST(TreeNode* root) { if (root == NULL) return root; midBST(root); return root; } void midBST(TreeNode* root) { if (root == NULL) return; midBST(root->right); root->val += preSum; preSum = root->val; midBST(root->left); } };