538 Convert BST to Greater Tree 把二叉搜索树转换为累加树
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 二叉搜索树:
5
/ \
2 13
输出: 转换为累加树:
18
/ \
20 13
详见:https://leetcode.com/problems/convert-bst-to-greater-tree/description/
C++:
方法一:
/** * 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 { public: TreeNode* convertBST(TreeNode* root) { int sum = 0; helper(root, sum); return root; } void helper(TreeNode*& node, int& sum) { if (!node) { return; } helper(node->right, sum); node->val += sum; sum = node->val; helper(node->left, sum); } };
方法二:
/** * 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 { public: TreeNode* convertBST(TreeNode* root) { if (!root) { return nullptr; } int sum = 0; stack<TreeNode*> stk; TreeNode *p = root; while (p || !stk.empty()) { while (p) { stk.push(p); p = p->right; } p = stk.top(); stk.pop(); p->val += sum; sum = p->val; p = p->left; } return root; } };
参考:http://www.cnblogs.com/grandyang/p/6591526.html