leetcode538

扫码查看
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
Stack<TreeNode> S = new Stack<TreeNode>(); private void postNode(TreeNode node)
{
if (node != null)
{
if (node.left != null)
{
postNode(node.left);
}
S.Push(node);
if (node.right != null)
{
postNode(node.right);
} }
} public TreeNode ConvertBST(TreeNode root)
{
postNode(root);
var list = S.ToList();
var sum=; foreach (var l in list)
{
sum += l.val;
l.val = sum;
} return root;
}
}

https://leetcode.com/problems/convert-bst-to-greater-tree/#/description

补充一个python的实现:

 class Solution(object):
def __init__(self):
self.total = def convertBST(self, root):
if root is not None:
self.convertBST(root.right)
self.total += root.val
root.val = self.total
self.convertBST(root.left)
return root
05-11 15:39
查看更多