+ -
当前位置:首页 → 问答吧 → 关于二叉树的问题

关于二叉树的问题

时间:2011-12-19

来源:互联网

二叉树的头文件以及完成相关操作的函数怎么写

作者: yw52109   发布时间: 2011-12-19

google

作者: quwei197874   发布时间: 2011-12-19

class Node{Node* lchild,*rchild;friend class.....}
class tree{Node* roof ....}

作者: sgy374805979   发布时间: 2011-12-19

大致就这样,还有两个操作没写完,也没有调试过,楼主参考一下吧:

C/C++ code

struct Tree {
    struct Node {
        int value ;
        Node * left , * right ;
        Node (int x) : value (x) , left ((Node*)NULL) , right ((Node*)NULL) {}
    } ;
    Node * root ;
    Tree () : root ((Node*)NULL) {}
    bool insert (int x) ;
    bool del (int x) ;
    bool find (int x) ;
    
    private :
    bool insert_iter (int x , Node * r) ;
    bool del_iter (int x , Node * r) ;
    bool find_iter (int x , Node * r) ;
} ;

bool Tree :: insert (int x) {
    return insert_iter (x , root) ;
}
bool Tree :: insert_iter (int x , Node * r) {
    if (r == (Node*)NULL) {
        r = new Node (x) ;
        return true ;
    }
    if (r->value == x) {
        return false ;
    }
    if (r->value < x) {
        return insert_iter (x , r->left) ;
    }
    if (r->value > x) {
        return insert_iter (x , r->right) ;
    }
    return false ;
}

作者: luochen1990   发布时间: 2011-12-20

测试了一下,发现个bug = =# ,重贴一下代码:
C/C++ code

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

struct Tree {
    struct Node {
        int value ;
        Node * left , * right ;
        Node (int x) : value (x) , left ((Node*)NULL) , right ((Node*)NULL) {}
    } ;
    Node * root ;
    Tree () : root ((Node*)NULL) {}
    bool insert (int x) ;
    bool del (int x) ;
    bool find (int x) ;
    
    private :
    bool insert_iter (int x ,  Node * & r) ;
    bool del_iter (int x ,  Node * & r) ;
    bool find_iter (int x ,  Node * & r) ;
} ;

bool Tree :: insert (int x) {
    return insert_iter (x , root) ;
}
bool Tree :: insert_iter (int x , Node * & r) {
    if (r == (Node*)NULL) {
        r = new Node (x) ;
        return true ;
    }
    if (r->value == x) {
        return false ;
    }
    if (r->value < x) {
        return insert_iter (x , r->left) ;
    }
    if (r->value > x) {
        return insert_iter (x , r->right) ;
    }
    return false ;
}


int main() {
    Tree t ;
    cout << t.insert(1) << endl ;
    cout << t.insert(2) << endl ;
    cout << t.insert(0) << endl ;
    cout << t.insert(4) << endl ;
    cout << t.insert(3) << endl ;
    cout << t.root->value << endl ;
    cout << t.root->left->value << endl ;
    cout << t.root->right->value << endl ;
    cout << t.root->left->left->value << endl ;
    cout << t.root->left->left->right->value << endl ;

    while(1) ;
    return 0 ;
}

作者: luochen1990   发布时间: 2011-12-20