• 538. Convert BST to Greater Tree


    一、题目

      1、审题

      

      

      2、分析

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

    二、解答

      思路:

        采用类似中序(左-->根-->右)遍历的方式。实际采用 (右--> 根 --> 左)。遍历时,统计所有遍历的节点之和。

      方法一、

        采用一个 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;
        }

      方法二、

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

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

      

        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;
        }

        

  • 相关阅读:
    asp.net发布和更新网站
    细说 Form (表单)
    python之面向对象进阶3
    python之面向对象进阶2
    python之面向对象进阶
    python之面向对象
    python之模块与包
    python之常用模块(续)
    python 之常用模块
    迭代器和生成器函数
  • 原文地址:https://www.cnblogs.com/skillking/p/10942132.html
Copyright © 2020-2023  润新知