7-10 Leaf node sum (30 points)

For a given binary tree with N nodes (N>=0), find the sum of the leaf node elements.

Input format: The
first line is a non-negative integer N, which means there are N nodes

The second line is an integer k, which is the element value of the root of the tree

Next, there are N-1 lines, each line is a new node, the format is rde three integers,

r represents the element value of the parent node of the node (the parent node is guaranteed to exist); d is the direction, 0 represents the node is the left son of the parent node, 1 represents the right son; e is the element value of the node.

Output format: the
sum of leaf node elements in the tree (guaranteed to be within the range of integer variables).

Input sample:

Insert picture description here

For the binary tree in the picture:

3
20
20 0 10
20 1 25

Sample output:

35

Routine questions, save each node, when inputting, traverse the stored nodes, change the left and right nodes, pay attention to output 0 when the tree is empty, and then exit the program directly.
#include <iostream>
#include <vector>
using namespace std;

typedef struct Node {
    
    
    int data;
    struct Node *left;
    struct Node *right;
} Node, *Tree;

int main() {
    
    
    int n;
    cin >> n;
    if(n == 0){
    
    
        cout << 0;
        return 0;
    }
    vector<Tree> v;
    Tree root = (Tree)malloc(sizeof(Node));
    int k, r, d, e;
    cin >> k;
    root->data = k;
    root->left = root->right = NULL;
    v.push_back(root);
    for (int i = 1; i < n; i++) {
    
    
        Tree tmp = (Tree)malloc(sizeof(Node));
        cin >> r >> d >> e;
        tmp->data = e;
        tmp->left = tmp->right = NULL;
        for (int j = 0; j < v.size(); j++) {
    
    
            if (v[j]->data == r) {
    
    
                if (d == 0)
                    v[j]->left = tmp;
                else
                    v[j]->right = tmp;
                break;
            }
        }
        v.push_back(tmp);
    }
    int sum = 0;
    for (int i = 0; i < v.size(); i++) {
    
    
        if (!v[i]->left && !v[i]->right)
            sum += v[i]->data;
    }
    cout << sum;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45845039/article/details/111569134