经典算法-二叉树(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
}
相关文章
相关标签/搜索