經典算法-二叉樹(golang)

package main

func main() {

}

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

// 938. Range Sum of BST  二叉搜索樹的範圍和
//Input: root = [10,5,15,3,7,null,18], L = 7, R = 15    Output: 32
//Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10    Output: 23
func rangeSumBST(root *TreeNode, L int, R int) int {
    if root == nil {
        return 0
    }
    if root.Val > R {
        return rangeSumBST(root.Left, L, R)
    }
    if root.Val < L {
        return rangeSumBST(root.Right, L, R)
    }
    return root.Val + rangeSumBST(root.Left, L, R) + rangeSumBST(root.Right, L, R)
}


// 617. Merge Two Binary Trees    合併二叉樹
//Input:
//        Tree 1                  Tree 2
//         1                         2
//        / \                       / \
//       3   2                     1   3
//      /                           \   \
//   5                             4   7
//Output:
//        Merged tree:
//               3
//              / \
//             4   5
//            / \   \
//            5   4   7
func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode {
    if t1 == nil { // 若是t1爲空,t2非空,那麼咱們就以t2的結點值創建一個新結點
        return t2
    }
    if t2 == nil { // 若是t2爲空,t1非空,那麼咱們就以t1的結點值創建一個新結點
        return t1
    }
    // 若是t1和t2都非空,那麼咱們就以t1和t2的結點值之和創建一個新結點,而後分別對t1的左右子結點和t2的左右子結點調用遞歸函數
    return &TreeNode{t1.Val + t2.Val, mergeTrees(t1.Left, t2.Left), mergeTrees(t1.Right, t2.Right)}
}

// 104. Maximum Depth of Binary Tree    求二叉樹高度
// 思路:很簡單,當前結點深度等於左右子樹中較大的那個深度加一。
func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }
    left := maxDepth(root.Left)
    right := maxDepth(root.Right)
    if left > right {
        return left + 1
    } else {
        return right + 1
    }

}

// 226. Invert Binary Tree    反轉二叉樹
// 思路:遞歸互換左右子節點
//Example:
//
//Input:                        Output:
//
//        4                          4
//      /   \                        /   \
//      2    7                   7     2
//     / \   / \                  / \   / \
//    1   3 6   9                 9   6 3   1
func invertTree(root *TreeNode) *TreeNode {
    if root == nil {
        return root
    }
    root.Left, root.Right = invertTree(root.Right), invertTree(root.Left)
    return root
}

// 538. Convert BST to Greater Tree        二叉查找樹轉化爲更大樹
// 思路:二叉查找樹右邊子節點比節點數值大,遞歸全部右節點的累加和 右-中-左遍歷相加
func convertBST(root *TreeNode) *TreeNode {
    node, _ := traverse(root, 0)
    return node
}

func traverse(root *TreeNode, sum int) (*TreeNode, int) {
    if root == nil {
        return nil, sum
    }

    _, sum = traverse(root.Right, sum)
    root.Val += sum
    sum = root.Val
    _, sum = traverse(root.Left, sum)

    return root, sum
}
相關文章
相關標籤/搜索