zoukankan      html  css  js  c++  java
  • 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;
        }

        

  • 相关阅读:
    固态硬盘 每秒1.5G
    editPlus
    juqery 插入一行
    BufferedReader读取UTF8文件中文乱码
    jquery table 操作
    noSql
    javascript 开发规范
    同一服务器上安装多个tomcat
    100 个搜索引擎
    firefox 开发sdk
  • 原文地址:https://www.cnblogs.com/skillking/p/10942132.html
Copyright © 2011-2022 走看看