二叉树删除节点

 

#include <iostream>
#include <string>
using namespace std;

struct TreeNode{
    int data;
    TreeNode *lchild;
    TreeNode *rchild;
};

TreeNode *findMin(TreeNode *&root){
    while (root->lchild)
        root = root->lchild;
    return root;
}

void DeleteNode(TreeNode *root, int x){
    if (!root)
        return ;

    if (x < root->data)
        DeleteNode(root->lchild, x);
    else if (x > root->data)
        DeleteNode(root->rchild, x);
    else if (root->lchild && root->rchild){
        TreeNode *min = findMin(root->rchild);
        root->data = min->data;
        DeleteNode(root->rchild, min->data);        
    }
    else{
        TreeNode *p = root;
        root = root->lchild ? root->lchild : root->rchild;
        delete p;
    }
}

int main()
{
    
    return 0;
}

 

 

 

 

 

EOF

posted on 2012-12-19 22:53  kkmm  阅读(350)  评论(0编辑  收藏  举报