说实话,本题没有做出来真的是不应该,可能是太困了
因为是一道Easy题,直接用recusive遍历即可
而且思路也不难:
- 就是以右 -> 中 -> 左的顺序访问即可,顺便用一个累加器来累加
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int accumulator;
public TreeNode convertBST(TreeNode root) {
accumulator = 0;
DFSHelper(root);
return root;
}
private void DFSHelper(TreeNode root) {
if (root == null) {
return;
}
DFSHelper(root.right);
accumulator += root.val;
root.val = accumulator;
DFSHelper(root.left);
}
}