1110. Complete Binary Tree (25)

简介: #include #include #include #include using namespace std;struct node { int ad, l, r; };vector visited(20, ...
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

struct node { int ad, l, r; };
vector<bool> visited(20, false);
vector<node> nodes;
int n,root = 0;

int main(){
    cin >> n;
    nodes.resize(n);
    for (int i = 0; i < n; i++) {
        string l, r;
        cin >> l >> r;
        if(l != "-"){
            nodes[i].l = stoi(l);
            visited[stoi(l)] = true;
        }else nodes[i].l = -1;
        if(r != "-"){
            nodes[i].r = stoi(r);
            visited[stoi(r)] = true;
        }else nodes[i].r = -1;
    }
    for(int i = 0; i < n; i++)
        if(visited[i] == 0) { root = i; break; }

    //层序遍历的思想
    queue<int> q;
    q.push(root);
    int cnt = 0;
    int lastnode = 0;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        if (node != -1) {
            lastnode = node;
            cnt++;
        }else{
            if(cnt != n)
                printf("NO %d\n", root);
            else
                printf("YES %d\n", lastnode);
            return 0;
        }
        q.push(nodes[node].l);
        q.push(nodes[node].r);
    }

    return 0;
}
目录
相关文章
|
存储
|
存储
LeetCode 107. Binary Tree Level Order Traversal II
给定二叉树,返回其节点值的自下而上级别顺序遍历。 (即,从左到右,逐下而上)。
79 0
LeetCode 107. Binary Tree Level Order Traversal II
LeetCode 222. Count Complete Tree Nodes
给出一个完全二叉树,求出该树的节点个数。
90 0
LeetCode 222. Count Complete Tree Nodes
|
存储 算法
PAT (Advanced Level) Practice - 1151 LCA in a Binary Tree(30 分)
PAT (Advanced Level) Practice - 1151 LCA in a Binary Tree(30 分)
127 0
PAT (Advanced Level) Practice - 1043 Is It a Binary Search Tree(25 分)
PAT (Advanced Level) Practice - 1043 Is It a Binary Search Tree(25 分)
124 0
【1064】Complete Binary Search Tree (30 分)
【1064】Complete Binary Search Tree (30 分) 【1064】Complete Binary Search Tree (30 分)
100 0
|
机器学习/深度学习
1064. Complete Binary Search Tree (30)
#include #include #include using namespace std; const int maxn = 1001; vector num(maxn), cbt(maxn); int n, c...
846 0
[LeetCode] Recover Binary Search Tree
As the note in the problem statement, this problem has a straight-forward O(n)-space solution, which is to generate the inorder traversal results of t...
673 0
leetcode 102 Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
913 0