Topicinserting nodes in a binary lookup tree
Given a binary lookup tree and a new tree node, insert the node into the tree.
You need to make sure that the tree is still a binary search tree.
Sample Example
Give the following binary search tree, after inserting node 6, this binary search tree can be this:
2 2 / \ / 1 4 --> 1 4 / / \ 3 3 6
The two methods of recursive and non-recursive analysis are implemented.
Python code
"" "Definition of Treenode:class treenode:def __init__ (Self, val): Self.val = Val self.left, self.right = None, none "" "Class Solution:" "@param root:the root of the binary search tree. @param node:insert This node into the binary search tree. @return: The root of the new binary search tree. "" "Def insertNode1 (self, Root, node): # Write your code this if root is None:root = node return root if node.val < Root.val:root.left = Self.insertnode1 (root.left, node) else : Root.right = self.insertnode1 (root.left, node) return root def insertnode (self, Root, node): # Write your code here if Root was None:root = node return root t = root while T is not none:if Node.val < t.val:if t.left is None:t.left = node return root else: t = T.left Continue else:if t.right is None:t.right = node return root else:t = T.right Continue return root
GitHub-Python code
C + + code
/** * Definition of TreeNode: * Class TreeNode {* Public: * int val; * TreeNode *left, *right; * TreeNode (int val) {* This->val = val; * This->left = This->right = NULL; *} *} */class Solution {Publi C:/** * @param root:the root of the binary search tree. * @param node:insert This node into the binary search tree * @return: The root of the new binary search tree. */treenode* InsertNode1 (treenode* root, treenode* node) {//write your code here if (root = NULL) {root = node; return root; }//if if (Node->val < Root->val) {if (Root->left = = NULL) { root->left = node; }else{root->left = insertNode1 (root->left, node); }//else}else{if (root->right = = NULL) {root->right = node; }else{ Root->right = InsertNode1 (root->right, node); }//else}//else return root; }//Non-recursive treenode* insertnode (treenode* root, treenode* node) {//write your code here if (root = = NULL) {root = node; return root; }//if TreeNode *t = root; while (t! = NULL) {if (Node->val < T->val) {if (t-> left = = NULL) {t->left = node; return root; }else{T = t->left;; Continue }//else}//if else{if (t->right = = NULL) {T-> ; right = node; return root; }else{T = t->right; Continue }//else}//else}//while return root; }};
GitHub--C + + code
Lintcode (85) inserting nodes in a binary lookup tree