538. Convert BST to Greater Tree

1、题目node

  一、审题spa

  

  

  二、分析code

    给出一棵二叉搜索树。将全部节点值加上比他大的全部节点值。blog

 

2、解答递归

  思路:class

    采用相似中序(左-->根-->右)遍历的方式。实际采用 (右--> 根 --> 左)。遍历时,统计全部遍历的节点之和。变量

 

  方法1、二叉树

    采用一个 Stack 进行二叉树遍历。同时更新节点值。搜索

    public TreeNode convertBST(TreeNode root) {
        
        Stack<TreeNode> stack = new Stack<>();
        int sum = 0;
        TreeNode node = root;
        while(!stack.isEmpty() || node != null) {
            while(node != null) {
                stack.add(node);
                node = node.right;
            }
            
            node = stack.pop();
            node.val += sum;
            sum = node.val;
            node = node.left;
        }
        return root;
    }

 

  方法2、遍历

    ① 采用一个全局变量,统计遍历的节点值之和。

    ② 采用递归方式进行二叉树遍历。

  

    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if(root == null)
            return null;
        convertBST(root.right);
        root.val += sum;
        sum = root.val;
        convertBST(root.left);
        return root;
    }
相关文章
相关标签/搜索