【題目描述】
Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.
給定一棵具有不同節(jié)點值的二叉查找樹具被,刪除樹中與給定值相同的節(jié)點豆混。如果樹中沒有相同值的節(jié)點痊焊,就不做任何處理。你應(yīng)該保證處理之后的樹仍是二叉查找樹霍骄。
【題目鏈接】
www.lintcode.com/en/problem/remove-node-in-binary-search-tree/
【題目解析】
首先根據(jù)BST(二叉查找樹)的性質(zhì),找到目標(biāo)節(jié)點cur及其父節(jié)點pre
如果cur不存在,則直接返回root榄笙。記ncur為取代cur位置的節(jié)點识藤,默認(rèn)令ncur = cur.right砚著。如果cur擁有左孩子,則將其右孩子鏈接到左孩子的最大子節(jié)點的右側(cè)痴昧,令cur = cur.left稽穆。然后修正pre與ncur之間的關(guān)系。
【參考答案】
www.jiuzhang.com/solutions/remove-node-in-binary-search-tree/