【LeetCode每日一题】538. 把二叉搜索树转换为累加树

【LeetCode每日一题】538. 把二叉搜索树转换为累加树

538. 把二叉搜索树转换为累加树

题目来源link
算法思想:树,右中左(反中序遍历)

二叉搜索树中序遍历(左中右)得到序列由小到大;
反中序遍历(右中左)得到序列由大到小;
在使用sum做叠加组合即可;

java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
    
    
		dfsBST(root);
		return root;
    }
    
	public void dfsBST(TreeNode root) {
    
    
		if(root == null) {
    
    
			return;
		}
		dfsBST(root.right);//反中序遍历,先遍历右子树
		root.val = root.val + sum;//叠加
        sum = root.val;//将值保存,下一个结点计算
		dfsBST(root.left);//反中序遍历,遍历左子树
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39457586/article/details/108703754