funcdfs(root *TreeNode, v int)int { if root == nil { return v } r := dfs(root.Right, v) root.Val += r l := dfs(root.Left, root.Val) return l }
时间复杂度: \(O(n)\),
将树中结点数量记为 \(n\),
需要每个结点遍历一次
空间复杂度: \(O(n)\),
递归栈开销
迭代
递归可以转化为显式的栈来实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Code language: Python classSolution: defconvertBST(self, root: TreeNode) -> TreeNode: cur = root s = 0 stack = [] while cur: stack.append(cur) cur = cur.right while stack: cur = stack.pop() s += cur.val cur.val = s cur = cur.left while cur: stack.append(cur) cur = cur.right return root
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Code language: Java classSolution { public TreeNode convertBST(TreeNode root) { TreeNode cur; intsum=0; Stack<TreeNode> s = newStack<TreeNode>(); for (cur = root; cur != null; cur = cur.right) s.add(cur); while (!s.empty()){ cur = s.pop(); sum += cur.val; cur.val = sum; for (cur = cur.left; cur != null; cur = cur.right) s.add(cur); } return root; } }
// Code language: C++ classSolution { public: TreeNode* convertBST(TreeNode* root){ TreeNode* cur; int sum = 0; stack<TreeNode*> s; for (cur = root; cur != nullptr; cur = cur->right) s.emplace(cur); while (!s.empty()){ cur = s.top(); s.pop(); sum += cur->val; cur->val = sum; for (cur = cur->left; cur != nullptr; cur = cur->right) s.emplace(cur); } return root; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Code language: Go funcconvertBST(root *TreeNode) *TreeNode { var s = 0 var st []*TreeNode for cur := root; cur != nil; cur = cur.Right { st = append(st, cur) } forlen(st) > 0 { cur := st[len(st)-1] st = st[:len(st)-1] s += cur.Val cur.Val = s for cur = cur.Left; cur != nil; cur = cur.Right { st = append(st, cur) } } return root }