二叉排序树

二叉排序树

http://www.nowcoder.com/questionTerminal/30a0153649304645935c949df7599602

本题考察的是二叉树的建立,并且输出父节点的值。所以函数Insert的参数里多了一个int型的变量father,记录的是父节点的值。因为二叉排序树的新增节点都是在叶子处,所以root == NULL时,新建一个结点BTree(x)。

// runtime: 5ms
// space: 504K
#include <iostream>
using namespace std;

struct BTree {
    int data;
    BTree* leftChild;
    BTree* rightChild;
    BTree(int x) : data(x), leftChild(NULL), rightChild(NULL) {}
};

BTree* Insert(BTree* root, int x, int father) {
    if (root == NULL) {
        root =  new BTree(x);
        cout<< father <<endl;
    } else if (root->data > x) {
        root->leftChild = Insert(root->leftChild, x, root->data);
    } else {
        root->rightChild = Insert(root->rightChild, x, root->data);
    }
    return root;
}

int main() {
    int n;
    while (cin>> n) {
        BTree* root = NULL;
        for (int i = 0; i < n; ++i) {
            int x;
            cin>> x;
            root = Insert(root, x, -1); // 每次都从根开始,用-1表示
        }
    }
    return 0;
}
全部评论

相关推荐

12-23 18:51
中南大学 Java
唉又萌混过关:是不是那种收钱盖实习章的机构?
点赞 评论 收藏
分享
评论
12
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务