前言
遍历二叉树是操作树的基础,一切树操作不过是在遍历的基础上进行变种操作。
一、把二叉搜索树转换为累加树
二、逆中序遍历
记录当前的累加值,再逆中序遍历的过程中,不断更新root节点和累加值,便可完成累加修改,每次返回当前root,入口本就是root,左右遍历完又回到真root处,返回即可。
/**
* 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 {
int cur = 0;
public TreeNode convertBST(TreeNode root) {
if(null == root) return null;
convertBST(root.right);
root.val += cur;
cur = root.val;
convertBST(root.left);
return root;
}
}
注:设置一个preSum值传入递归函数,不断更新并返回preSum,也可回溯累加。
总结
1)二叉树的遍历是基础也是核心。