刪除二叉查詢樹的節點
阿新 • • 發佈:2018-12-24
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1.刪除節點函式需要有節點的父節點和結點兩個屬性,並且分兩種情況:</span>
①當刪除節點的右節點為空時,刪除節點時直接將刪除節點的左節點替換刪除節點
②當刪除節點的右節點不空時,找到刪除節點的右節點的最小(最左節點)替換被刪除節點,並刪除最左節點
<span style="font-family: Arial, Helvetica, sans-serif;">public TreeNode removeNode(TreeNode root, int value) {</span>
TreeNode dummy = new TreeNode(0); dummy.left = root; TreeNode parent = findNode(dummy, root, value); TreeNode node; if (parent.left != null && parent.left.val == value) { node = parent.left; } else if (parent.right != null && parent.right.val == value) { node = parent.right; } else { return dummy.left; } deleteNode(parent, node); return dummy.left; } private TreeNode findNode(TreeNode parent, TreeNode node, int value) { if (node == null) { return parent; } if (node.val == value) { return parent; } if (value < node.val) { return findNode(node, node.left, value); } else { return findNode(node, node.right, value); } } private void deleteNode(TreeNode parent, TreeNode node) { if (node.right == null) { if (parent.left == node) { parent.left = node.left; } else { parent.right = node.left; } } else { TreeNode temp = node.right; TreeNode father = node; while (temp.left != null) { father = temp; temp = temp.left; } if (father.left == temp) { father.left = temp.right; } else { father.right = temp.right; } if (parent.left == node) { parent.left = temp; } else { parent.right = temp; } temp.left = node.left; temp.right = node.right; } }