LeetCode - Insert into a Binary

2019-07-22  本文已影响0人  Andy1944

Insert into a Binary Search Tree - LeetCode

Solution

class Solution {
    func insertIntoBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {
        var root = root
        insertIntoBST(&root, val)
        return root
    }
    
    func insertIntoBST(_ root: inout TreeNode?, _ val: Int) {
        guard let root = root else {
            return
        }
        if val < root.val {
            if root.left == nil {
                root.left = TreeNode(val)
            } else {
                insertIntoBST(&root.left, val)
            }
        } else {
            if root.right == nil {
                root.right = TreeNode(val)
            } else {
                insertIntoBST(&root.right, val)
            }
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读