本文主要是介绍Add, Search, Delete Node in BST.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Add Node, Search Node, Delete Node, 的基本操作,被问了两次了。写出来。
http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/
// add the node;public TreeNode addNode(TreeNode root, int val) {if(root == null){root = new TreeNode(val);return root;}if(root.val == val) {return root;} else if(root.val > val) {root.left = addNode(root.left, val);} else { // root.val < val;root.right = addNode(root.right, val);}return root;}// search the node;public TreeNode searchNode(TreeNode root, int val) {if(root == null || root.val == val) {return root;}if(val < root.val){return searchNode(root.left, val);} else {return searchNode(root.right, val);}}
http://quiz.geeksforgeeks.org/binary-search-tree-set-2-delete/
delete node分三类,如上,左右两边都有的,那么就找最右边的最小的,copy到root,然后delete那个node;
// delete node; public TreeNode deleteNode(TreeNode root, int val) {if(root == null) return root;if(val < root.val){root.left = deleteNode(root.left, val);} else if(val > root.val) {root.right = deleteNode(root.right, val);} else { // root.val == val, find the treenode that needs to be deleted;if(root.left == null) {return root.right;} else if(root.right == null) {return root.left;} else { // root has left & right node;root.val = findInorderNextNode(root.right);root.right = deleteNode(root.right, root.val);}}return root;}
这篇关于Add, Search, Delete Node in BST.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!