阅读背景:

树寻找根节点

来源:互联网 
//
//  main.cpp
//  寻找根节点
//
//  Created by liujan on 1/13/15.
//  Copyright (c) 2015 liujan. All rights reserved.
//

#include <iostream>
#include "memory.h"
using namespace std;

/*
 *每个节点的id在输入父节点时被输入一次,输入本身时一次,两个子节点时又两次,所以其输入次数肯定为偶数
 *根节点只会被输入奇数次
 */
int findRoot1(int n){
    int *isroot = new int[n*n];
    memset(isroot, 0, sizeof(isroot));
    for (int i = 0; i < n; i++){
        int id, l, r;
        cin >> id >> l >> r;
        isroot[id]++;
        isroot[l]++;
        isroot[r]++;
    }
    int root;
    for (int i = 0; i < n*n; i++){
        if (isroot[i] % 2 != 0)
            root = i;
    }
    return root;
}
/*
 *先把所有节点的父节点设为-1,在输入节点时再设置每个节点的父节点
 *最后父节点仍为-1的那个点肯定是根节点
 */
int findRoot2(int n){
    int *root = new int[n*n];
    memset(root, -1, sizeof(root));
    for (int i = 0; i < n; i++){
        int id, l, r;
        cin >> id >> l >> r;
        root[l] = id;
        root[r] = id;
    }
    int rootid = 0;
    for (int i = 0; i < n*n; i++){
        if (root[i] == -1){
            rootid = i;
        }
    }
    return rootid;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}
//
//  main.cpp
//  寻找根节点
//
//  Created by liu



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: