删除二叉树的子树

#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
struct Node{
    int val;
    Node *left;
    Node *right;
    explicit Node(int value):val(value),left(nullptr),right(nullptr){}
};

Node *creatTree(){
    Node *head = new Node(1);
    head->left = new Node(2);
    head->right = new Node(3);
    head->left->left  = new Node(4);
    head->left->right = new Node(5);
    head->right->left = new Node(6);
    head->right->right = new Node(7);
    return head;
}
void delectTree(Node *node);
void boardOrder(Node *head, int value){
    if(head == nullptr){
        return ;
    }
    queue<Node *> q;
    Node *father;
    q.push(head);
    while(!q.empty()){
        auto node = q.front();
        if(node -> val == value){
            if(father->left == node){
                father->left = nullptr;
                delectTree(node);
            }
            if(father->right == node){
                father->right = nullptr;
                delectTree(node);
            }
            break;
        }
        q.pop();
        if(node->left != nullptr){
            q.push(node->left);
        }
        if(node -> right != nullptr){
            q.push(node->right);
        }
        father = node;
    }
}

void delectTree(Node *node){
    if(node == nullptr){
        return;
    }
    delectTree(node->left);
    delectTree(node->right);
    delete(node);
}

int main() {
    auto head = creatTree();
    boardOrder(head, 2);
    return 0;
}
上一篇:C++学习记录 - 智能指针


下一篇:C++11学习小笔记