/** * 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=0; foreach (var l in list) { sum += l.val; l.val = sum; } return root; } }
https://leetcode.com/problems/convert-bst-to-greater-tree/#/description
补充一个python的实现,思路:使用中序遍历,在递归过程中累加节点和。
其实是把第一种方案的代码的两次循环合并成了一次,都是使用中序遍历的思想。
1 class Solution(object): 2 def __init__(self): 3 self.total = 0 4 5 def convertBST(self, root): 6 if root is not None: 7 self.convertBST(root.right) 8 self.total += root.val 9 root.val = self.total 10 self.convertBST(root.left) 11 return root