您的位置:首页 > Web前端 > Node.js

[刷题]Insert Node in a Binary Search Tree

2015-03-30 18:50 399 查看
[LintCode]Insert
Node in a Binary Search Tree

/**
* 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) {
// 2015-3-30
if (node == null) {
return root;
}
if (root == null) {
return node;
}

TreeNode temp = root;
TreeNode last = null;
boolean left = true;
while (temp != null) {
if (temp.val < node.val) {
last = temp;
temp = temp.right;
left = false;
} else if (temp.val > node.val) {
last = temp;
temp = temp.left;
left = true;
} else {
return root;
}
}

if (left == true) {
last.left = node;
} else {
last.right = node;
}
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: