• 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

  • 相关阅读:
    cygwin 下配置ssh
    使用MarsEdit写博客
    bash no job control in this shell
    安装devtoolset-2:因由安装gcc 4.8而引起
    AFNetworking Property with 'retain (or strong)' attribute must be of object type
    从xib 创建 collectionViewCell
    CocoaPods 安装
    个人理解的 Https 通信流程
    cellforrowatindexpath 不执行 的原因
    do{} while(0) 的意义和用法
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8910068.html
Copyright © 2020-2023  润新知