zoukankan      html  css  js  c++  java
  • 538. 把二叉搜索树转换为累加树

    给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

    例如:

    输入: 原始二叉搜索树:
      5
    /
    2 13

    输出: 转换为累加树:
      18
    /
    20 13

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private int num = 0;
        public TreeNode convertBST(TreeNode root) {
            if(root == null)
                return null;
            convert(root);
            return root;        
        }
        public void convert(TreeNode root)
        {
            if(root == null)
                    return;
            convert(root.right);
            root.val = root.val + num;
            num = root.val;
            convert(root.left);    
        }
    }
  • 相关阅读:
    记账本开发第一天-补
    20200418-补
    20200411-补
    20200404-补
    20200328-补
    暴力解N皇后
    nN皇后递归
    Hanoi汉诺塔非递归栈解
    Hanoi汉诺塔递归
    JMMjmm模型
  • 原文地址:https://www.cnblogs.com/Duancf/p/12466020.html
Copyright © 2011-2022 走看看