美文网首页
Leetcode-538Convert BST to Great

Leetcode-538Convert BST to Great

作者: LdpcII | 来源:发表于2018-04-20 01:40 被阅读0次

538. Convert BST to Greater Tree

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
              5
            /   \
           2     13

Output: The root of a Greater Tree like this:
             18
            /   \
          20     13

My Solution(C/C++)

#include <iostream>
#include <cstdio>

using namespace std;

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 val = 0;
        changeBST(root, val);
        return root;
    }
    void printTreeNode(TreeNode* root, int level) {  //打印二叉树
        if (!root) {
            return;
        }
        for (int i = 0; i < level; i++) {
            printf("-");
        }
        printf(" %d\n", root->val);
        printTreeNode(root->left, level + 1);
        printTreeNode(root->right, level + 1);
    }
private:
    void changeBST(TreeNode* node, int &val) {
        if (!node) {
            return;
        }
        changeBST(node->right, val);
        node->val += val;
        val = node->val;
        changeBST(node->left, val);
    }
};

int main() {
    Solution s;
    TreeNode a(5);
    TreeNode b(3);
    TreeNode c(6);
    TreeNode d(2);
    TreeNode e(4);
    TreeNode f(7);
    a.left = &b;
    b.left = &d;
    b.right = &e;
    a.right = &c;
    c.right = &f;
    TreeNode *result;
    result = s.convertBST(&a);
    s.printTreeNode(result, 0);
    return 0;
}

结果

 18
- 25
-- 27
-- 22
- 13
-- 7

My Solution(Python)

sum = 0
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def convertBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        self.getBST(root)
        global sum
        sum = 0
        return root

    def getBST(self, root):
        # 右中左
        if not root:
            return
        self.getBST(root.right)
        global sum
        root.val = root.val + sum
        sum = root.val
        self.getBST(root.left)

相关文章

网友评论

      本文标题:Leetcode-538Convert BST to Great

      本文链接:https://www.haomeiwen.com/subject/ewmnkftx.html