zoukankan      html  css  js  c++  java
  • LeetCode 538----Convert BST to Greater Tree

    Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

    Example:

    Input: The root of a Binary Search Tree like this:


    5
    /
    2 13

    Output: The root of a Greater Tree like this:

    18 / 20 13

    算法分析:

    用"中序遍历"的方式访问每个节点的值,并将该节点的值累加到一个 int sum 变量上,并用该 sum 变量更新该节点的值。要注意的是,此处的中序遍历是先遍历右子树,再访问根节点,然后再遍历左子树(因为 BST 根节点的值小于右子树所有节点的值,大于左子树所有节点的值)。

    Java 算法实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        int sum=0;
        public TreeNode convertBST(TreeNode root) {
            sum=0;
            addSum(root);
            return root;
        }
        
        public void addSum(TreeNode root){
        	if(root!=null){
        		addSum(root.right);
        		sum+=root.val;
        		root.val=sum;
        		addSum(root.left);
        		
        	}
        }
    }
  • 相关阅读:
    时间复杂度和空间复杂度
    七、vue计算属性
    六、vue侦听属性
    四、vue派发更新
    五、vue nextTick
    三、vue依赖收集
    二、vue响应式对象
    递归
    链表
    TypeScript类型定义文件(*.d.ts)生成工具
  • 原文地址:https://www.cnblogs.com/dongling/p/6579689.html
Copyright © 2011-2022 走看看