给定一棵具有不同节点值的二叉查找树,删除树中与给定值相同的节点。如果树中没有相同值的节点,就不做任何处理。你应该保证处理之后的树仍是二叉查找树。
样例:
#ifndef C87_H
#define C87_H
#include<iostream>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int val){
this->val = val;
this->left = this->right = NULL;
}
};
class Solution {
public:
TreeNode* removeNode(TreeNode* root, int value) {
// write your code here
TreeNode *head = new TreeNode(NULL);
head->left = root;
TreeNode *p = root, *q = p;
int i = 0;
while (p != NULL)
{
if (value > p->val)
{
q = p;
p = p->right;
i = 1;
}
else if (value == p->val)
{
break;
}
else
{
q = p;
p = p->left;
i = 0;
}
}
if (p == NULL)
return root;
else
{
if (p->left == NULL&&p->right == NULL)
{
if (i == 0)
q->left = NULL;
else
q->right = NULL;
}
else if (p->left != NULL&&p->right == NULL)
{
if (i == 0)
q->left = p->left;
else
q->right = p->left;
}
else if (p->left == NULL&&p->right != NULL)
{
if (i == 0)
q->left = p->right;
else
q->right = p->right;
}
else
{
TreeNode *next = getNextNode(root, p->val);
TreeNode *parent = getParentNode(root, p->val);
if (next->right != NULL)
{
parent->left = next;
}
p->val = next->val;
}
}
return head->left;
}
TreeNode *getParentNode(TreeNode* root, int value)
{
TreeNode *p = root, *q = NULL;
while (p != NULL)
{
if (value < p->val)
{
q = p;
p = p->left;
}
else if (value == p->val)
break;
else
{
q = p;
p = p->right;
}
}
return q;
}
TreeNode* getLeftNode(TreeNode* root)
{
if (root == NULL) return NULL;
while (root->left != NULL)
root = root->left;
return root;
}
TreeNode* getNode(TreeNode* root, int value, TreeNode*& parent, TreeNode*& firstlParent)
{
while (root)
{
if (root->val == value)
return root;
parent = root;
if (root->val<value)
{
root = root->right;
}
else{
firstlParent = root;
root = root->left;
}
}
return NULL;
}
TreeNode* getNextNode(TreeNode* root, int value)
{
if (root)
{
TreeNode* parent = NULL;
TreeNode* firstlParent = NULL;
TreeNode* node = getNode(root, value, parent, firstlParent);
if (node == NULL)
return node;
if (node->right)
return getLeftNode(node->right);
if (NULL == parent || (parent && (NULL == firstlParent))) return NULL;
if (node == parent->left)
return parent;
else
{
return firstlParent;
}
}
return root;
}
};
#endif