p63 将二叉搜索树转化为累加树 (较大树) (leetcode 538)

一:解题思路

方法一:递归法:Time:O(n),Space:O(n)

方法二:迭代法:Time:O(n),Space:O(n)

二:完整代码示例 (C++版和Java版)

递归C++:

class Solution {
public:
    int dfs(TreeNode* root, int sum)
    {
        if (root == NULL) return sum;
        int cur = dfs(root->right,sum);
        root->val +=cur;
        return dfs(root->left,root->val);
    }

    TreeNode* convertBST(TreeNode* root) 
    {
        dfs(root,0);

        return root;
    }
};

递归Java:

class Solution {
    private int dfs(TreeNode root,int sum)
    {
        if(root==null) return sum;
        int cur=dfs(root.right,sum);
        root.val+=cur;
        return dfs(root.left,root.val);
    }

    public TreeNode convertBST(TreeNode root)
    {
           dfs(root,0);
        
           return root;
    }
}

迭代C++:

class Solution {
public:
    
    TreeNode* convertBST(TreeNode* root) 
    {
        stack<TreeNode*> stack;
        int sum = 0;
        TreeNode* cur = root;

        while (cur != NULL || !stack.empty())
        {
            while (cur != NULL)
            {
                stack.push(cur);
                cur = cur->right;
            }

            cur = stack.top();
            stack.pop();
            cur->val += sum;
            sum = cur->val;
            cur = cur->left;
        }

        return root;
    }
};

迭代Java:

class Solution {
    public TreeNode convertBST(TreeNode root)
    {
           Stack<TreeNode> stack=new Stack<>();
           int sum=0;
           TreeNode cur=root;

           while(cur!=null || !stack.empty())
           {
               while (cur!=null)
               {
                   stack.push(cur);
                   cur=cur.right;
               }

               cur=stack.pop();
               cur.val+=sum;
               sum=cur.val;
               cur=cur.left;
           }

           return root;
    }
}

 

posted @ 2020-03-19 17:26  repinkply  阅读(168)  评论(0)    收藏  举报