-
-
Save parcar/614f185fcdb0defbb4336705f24a7aa4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Definition for a binary tree node. | |
| # class TreeNode(object): | |
| # def __init__(self, x): | |
| # self.val = x | |
| # self.left = None | |
| # self.right = None | |
| class Solution(object): | |
| def insertIntoBST(self, root, val): | |
| """ | |
| :type root: TreeNode | |
| :type val: int | |
| :rtype: TreeNode | |
| """ | |
| if (root is None): | |
| return | |
| ms = [] | |
| ms.append(root) | |
| while (len(ms)): | |
| curr = ms.pop() | |
| if (curr.val < val and curr.right): | |
| ms.append(curr.right) | |
| elif (curr.val > val and curr.left): | |
| ms.append(curr.left) | |
| else: | |
| if(val > curr.val and curr.right == None): | |
| curr.right = TreeNode(val) | |
| return root | |
| elif(val < curr.val and curr.left == None): | |
| curr.left = TreeNode(val) | |
| return root | |
| else: | |
| print("Error") | |
| return | |
| ''' | |
| Runtime: 104 ms, faster than 50.03% of Python online submissions for Insert into a Binary Search Tree. | |
| Memory Usage: 15.8 MB, less than 86.67% of Python online submissions for Insert into a Binary Search Tree. | |
| ''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment