在二叉查找树中插入节点

来源:互联网 发布:城市poi数据 编辑:程序博客网 时间:2024/06/05 06:21
/** * 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){ root = node; return root; } TreeNode tmp = root; TreeNode last = null; while (tmp != null){ last = tmp; if (node.val > tmp.val){ tmp = tmp.right; } else { tmp = tmp.left; } } if (last != null){ if (last.val > node.val){ last.left = node; } else { last.right = node; } } return root; } }/** * 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; } if (root.val > node.val) { root.left = insertNode(root.left, node); } else { root.right = insertNode(root.right, node); } return root; }}
0 0
原创粉丝点击