代码如下:
recursive版本:
This file contains 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 of TreeNode: | |
* public class TreeNode { | |
* public int val; | |
* public TreeNode left, right; | |
* public TreeNode(int val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
* } | |
*/ | |
public 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. | |
*/ | |
public TreeNode insertNode(TreeNode root, TreeNode node) { | |
// write your code here | |
if (root == null) | |
return node; | |
if (node.val < root.val) | |
root.left = insertNode(root.left, node); | |
else if (node.val > root.val) | |
root.right = insertNode(root.right, node); | |
else | |
root.val = node.val; | |
return root; | |
} | |
} |
iterative版本:
This file contains 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 of TreeNode: | |
* public class TreeNode { | |
* public int val; | |
* public TreeNode left, right; | |
* public TreeNode(int val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
* } | |
*/ | |
public 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. | |
*/ | |
public TreeNode insertNode(TreeNode root, TreeNode node) { | |
if (root == null) | |
return node; | |
TreeNode curr = root; | |
while (true) { | |
if (node.val < curr.val) { | |
if (curr.left != null) | |
curr = curr.left; | |
else { | |
curr.left = node; | |
break; | |
} | |
} else if (node.val > curr.val) { | |
if (curr.right != null) | |
curr = curr.right; | |
else { | |
curr.right = node; | |
break; | |
} | |
} else { | |
curr.val = node.val; | |
break; | |
} | |
} | |
return root; | |
} | |
} |
No comments:
Post a Comment