leetcode 每日一题 450. 删除二叉搜索树中的节点
leetcode 每日一题 450. 删除二叉搜索树中的节点
class Solution { public TreeNode deleteNode(TreeNode root, int key) { if(root == null){ return null; } if(key == root.val){ if(root.left != null){ TreeNode rootLeftLastRight = right(root.left); rootLeftLastRight.right = root.right; return root.left; }else if(root.right != null){ return root.right; }else { return null; } } f(root,key,null,null); return root; } private void f(TreeNode root, int key,TreeNode parent,Boolean b) { if (root == null){ return; } //如果是这个要删除的节点 if(root.val == key){ //判断是父节点的左子节点还是右子节点 if(b){ //右边 if(root.right != null){ //循环找到最后一个节点,然后把左的节点挂过去 TreeNode rootRightLastLeft = left(root.right); rootRightLastLeft.left = root.left; parent.right = root.right; }else if(root.left != null){ parent.right = root.left; }else { parent.right = null; } }else{ //左边 if(root.left != null){ //循环找到最后一个节点,然后把右边的节点挂过去 TreeNode rootLeftLastRight = right(root.left); rootLeftLastRight.right = root.right; parent.left = root.left; }else if(root.right != null){ parent.left = root.right; }else { parent.left = null; } } } f(root.left,key,root,false); f(root.right,key,root,true); } private TreeNode left(TreeNode root) { if(root.left == null){ return root; } return left(root.left); } private TreeNode right(TreeNode root) { if(root.right == null){ return root; } return right(root.right); } }
改了几次,原因是左右节点的逻辑差不多,所以写的时候复制过去的,然后把right改成left,有部分代码没修改,导致一直测试出错




浙公网安备 33010602011771号