leetcode:701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
class Solution { public TreeNode insertIntoBST(TreeNode root, int val) {
//判断叶子结点,null说明到了,可以赋值。 if(root == null) { TreeNode node = new TreeNode(val); return node; } //判断val大小,决定去哪个节点 if(root.val < val ){ root.right = insertIntoBST(root.right,val); } if(root.val > val){ root.left = insertIntoBST(root.left, val); } return root; } }
leetcode:450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
class Solution { public TreeNode deleteNode(TreeNode root, int key) {
//5个情况,为空,root,left为空,右不为空,右为空,左不为空,找到节点时,用cur指针遍历到左叶子节点,将root指针right转移到left下来。 if (root == null) return root; if (root.val == key) { if (root.left == null) { return root.right; } else if (root.right == null) { return root.left; } else { TreeNode cur = root.right; while (cur.left != null) { cur = cur.left; } cur.left = root.left; root = root.right; return root; } } if (root.val > key) root.left = deleteNode(root.left, key); if (root.val < key) root.right = deleteNode(root.right, key); return root; } }
标签:right,return,val,root,二叉,搜索,树中,left From: https://www.cnblogs.com/lengbo/p/18076896