[LeetCode By Go 27]538. Convert BST to Greater Tree

二叉树的题目挺多的,写了个初始化二叉树的函数,以后用

func InitTree(index int, input []int) (t *TreeNode) {
    if index > len(input) {
        return nil
    }

    t = new(TreeNode)
    t.Val = input[index - 1]

    t.Left = InitTree(index*2, input)
    t.Right = InitTree(index*2 + 1, input)

    return t
}

题目

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

解题思路

二叉搜索树要求:每个节点都不比它左子树的任意元素小,而且不比它的右子树的任意元素大。
由大到小遍历二叉搜索树(右,中,左)二叉搜索树,题目要求操作就是该逆序遍历的当前节点加上之前所有节点的和。

因此,在逆序遍历的同时,累加得到一个总值sum,每个节点值加上这个总值
总值为全局变量,初始为0

代码

convertBST.go

package _538_Convert_BST_to_Greater_Tree

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

var sum int
func ReverseOrderAdd(t *TreeNode, add int){
    if nil == t {
        return
    }

    ReverseOrderAdd(t.Right, add)
    t.Val += sum
    sum = t.Val
    ReverseOrderAdd(t.Left, sum)

}
func ConvertBST(root *TreeNode) *TreeNode {
    sum = 0
    ReverseOrderAdd(root, 0)

    return root
}

测试

convertBST_test.go

package _538_Convert_BST_to_Greater_Tree

import (
    "testing"
    "fmt"
)

func InitTree(index int, input []int) (t *TreeNode) {
    if index > len(input) {
        return nil
    }

    t = new(TreeNode)
    t.Val = input[index - 1]

    t.Left = InitTree(index*2, input)
    t.Right = InitTree(index*2 + 1, input)

    return t
}

func MiddleOrder(t *TreeNode) {
    if nil == t {
        return
    }

    MiddleOrder(t.Left)
    fmt.Printf("%+v, ", t.Val)
    MiddleOrder(t.Right)
}

func TestConvertBST(t *testing.T) {

    input1 := []int{5, 2, 13}
    tree1 := InitTree(1, input1)

    input2 := []int{2,1,3}
    tree2 := InitTree(1, input2)

    var tests = []struct{
        root *TreeNode
    }{
        {tree1,},
        {tree2,},
    }

    for _, v := range tests {
        MiddleOrder(v.root)
        fmt.Println()
        ConvertBST(v.root)

        MiddleOrder(v.root)
        fmt.Println()
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/97a9d8c6e876
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞