LeetCode 538 把二叉搜索树转换为累加树 题解

LeetCode 538 把二叉搜索树转换为累加树 题解

LeetCode链接

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),
使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
输入: 原始二叉搜索树:
              5
            /   \
           2     13

输出: 转换为累加树:
             18
            /   \
          20     13

方法:

反向中序遍历,因为二叉搜索树的特点,中序遍历是一个递增的序列,反过来就是一个递减的序列,那么只要一边遍历,一遍加,一边更新val就可以了

1.递归

/**
 * 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) {
        if(root!=null){
            convertBST(root.right);
            sum+=root.val;
            root.val=sum;
            convertBST(root.left);
        }
        return root;
    }
}

2.morris反向中序遍历,强!

class Solution {
    public TreeNode convertBST(TreeNode root) {
        if(root==null){
            return root;
        }
        int sum=0;
        TreeNode cur=root;
        while(cur!=null){
            if(cur.right!=null){
                TreeNode pre=getPre(cur);
                //第一次到达
                if(pre.left==null){
                    pre.left=cur;
                    //先向右直到最右结点
                    cur=cur.right;
                }
                //第二次到达,说明右子树已经遍历完了
                else{
                    pre.left=null;
                    sum+=cur.val;
                    cur.val=sum;
                    //转向左子树
                    cur=cur.left;
                }
            }
            //没有右子树
            else{
                sum+=cur.val;
                cur.val=sum;
                cur=cur.left;
            }
        }
        return root;
    }
    //反向中序遍历的前驱结点是右子树的最左节点
    public TreeNode getPre(TreeNode root){
        TreeNode pre=root.right;
        while(pre.left!=null&&pre.left!=root){
            pre=pre.left;
        }
        return pre;
    }
}

版权声明:本文为qq_39618369原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。