33_把二叉搜索树转换为累加树

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

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

  • 节点的左子树仅包含键 小于 节点键的节点。
  • 节点的右子树仅包含键 大于 节点键的节点。
  • 左右子树也必须是二叉搜索树。

注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同

示例 1:

img

输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

示例 2:

输入:root = [0,null,1]
输出:[1,null,1]

示例 3:

输入:root = [1,0,2]
输出:[3,3,2]

示例 4:

输入:root = [3,2,4,1]
输出:[7,9,4,10]

递归法

class Solution {
   int sum = 0;
   public TreeNode convertBST(TreeNode root) {
       convertBST1(root);
       return root;
   }
   // 按右中左顺序遍历,累加即可
   public void convertBST1(TreeNode root) {
       if (root == null)
           return;
       convertBST(root.right);
       sum += root.val;
       root.val = sum;
       convertBST(root.left);
   }
}
//leetcode submit region end(Prohibit modification and deletion)

迭代法

class Solution {
    //DFS iteration统一迭代法
    public TreeNode convertBST(TreeNode root) {
        int pre = 0;
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) 
            return null;
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode curr = stack.peek();
            //curr!=null的情况,只负责存node到stack中
            if (curr != null) {
                stack.pop();
                if (curr.left != null)  //左
                    stack.add(curr.left);
                stack.add(curr); //中
                stack.add(null);
               if(curr.right != null)      //右
                    stack.add(curr.right);
            }else{
            //curr == null的状况,只负责做单层逻辑
                stack.pop();
                TreeNode temp = stack.pop();
                temp.val += pre;
                pre = temp.val;
            }
        }
        return root;
    }
}
posted @ 2024-01-24 21:20  鲍宪立  阅读(6)  评论(0编辑  收藏  举报