Leetcode538.-Convert BST to Greater Tree-Easy
阿新 • • 發佈:2020-08-05
題目:
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.
思路:
每個結點值加上所有比它大的結點值總和當作新的結點值。
初始化sum值 = 0
因為inorder traversal (left->root->right)結果是non decreasing 遞增數列,那麼逆過來right->root->left
程式碼:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * }*/ class Solution { private int sum = 0; public TreeNode convertBST(TreeNode root) { dfs(root); return root; } private void dfs(TreeNode root) { if(root == null) return; dfs(root.right); sum += root.val; root.val = sum; dfs(root.left); } }