美文网首页
LeetCode - Insert into a Binary

LeetCode - Insert into a Binary

作者: Andy1944 | 来源:发表于2019-07-22 17:08 被阅读0次

    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)
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode - Insert into a Binary

          本文链接:https://www.haomeiwen.com/subject/llgwlctx.html