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 105. Construct Binary Tree
给定一颗二叉树的前序和顺序遍历,构造原二叉树。 注意:您可以假设树中不存在重复项。
59 0
LeetCode 105. Construct Binary Tree
LeetCode 106. Construct Binary Tree
给定一颗二叉树的中序和后续遍历,构造原二叉树。 注意:您可以假设树中不存在重复项。
83 0
LeetCode 106. Construct Binary Tree
|
机器学习/深度学习
Data Structures (五) - 二叉树Binary Tree
Data Structures (五) - 二叉树Binary Tree
Data Structures (五) - 二叉树Binary Tree
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
PAT (Advanced Level) Practice - 1043 Is It a Binary Search Tree(25 分)
PAT (Advanced Level) Practice - 1043 Is It a Binary Search Tree(25 分)
135 0
|
算法 Python
Leetcode-Medium 98. Validate Binary Search Tree
Leetcode-Medium 98. Validate Binary Search Tree
134 0
【1064】Complete Binary Search Tree (30 分)
【1064】Complete Binary Search Tree (30 分) 【1064】Complete Binary Search Tree (30 分)
106 0
【1110】Complete Binary Tree (25分)【完全二叉树】
【1110】Complete Binary Tree (25分)【完全二叉树】 【1110】Complete Binary Tree (25分)【完全二叉树】
128 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...
851 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...
676 0