[关闭]
@snuffles 2019-04-02T14:15:22.000000Z 字数 430 阅读 791

把搜索二叉树转换为累加树


shenjin考试3.19

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

解:
5 => 18
/\ => /\
2 13 => 20 13
找规律,右中左是递增的,按照这个顺序遍历并相加,用int& sum来递归。

  1. class Solution {
  2. public:
  3. TreeNode* convertBST(TreeNode* root) {
  4. if(root == NULL) return root;
  5. int sum =0;
  6. newOrder(root,sum);
  7. return root;
  8. }
  9. void newOrder(TreeNode* root,int& sum){
  10. if(root == NULL) return ;
  11. newOrder(root->right,sum);
  12. //sum
  13. root->val += sum;
  14. sum = root->val;
  15. newOrder(root->left,sum);
  16. }
  17. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注