跳转至

DS二叉树--左叶子数量

时间限制: 1 Sec 内存限制: 128 MB

题目描述

计算一颗二叉树包含的叶子结点数量。

左叶子是指它的左右孩子为空,而且它是父亲的左孩子

提示:可以用三叉链表法,也可以用现有算法对两层结点进行判断

建树方法采用“先序遍历+空树用0表示”的方法

输入

第一行输入一个整数t,表示有t个测试数据

第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行

输出

逐行输出每个二叉树的包含的左叶子数量

样例输入

1
2
3
4
3
AB0C00D00
AB00C00
ABCD0000EF000

样例输出

1
2
3
0
1
2

提示

解决方案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>

class BiTree {
public:
    BiTree() : root(NULL) {}
    void assign(const std::string &string) {
        int index = 0;
        assign(string, index, root);
    }
    int leavesOfLeftChild() {
        int count = 0;
        leavesOfLeftChild(root, count);
        return count;
    }
private:
    struct Node {
        char data;
        Node *left, *right;
        Node() : data(0), left(NULL), right(NULL) {}
        explicit Node(char data) : data(data), left(NULL), right(NULL) {}
    };
    Node *root;
    void assign(const std::string &string, int &index, Node *&node) {
        char data = string[index++];
        if (data != '0') {
            node = new Node(data);
            assign(string, index, node->left);
            assign(string, index, node->right);
        } else {
            node = NULL;
        }
    }
    void leavesOfLeftChild(Node *node, int &count) {
        if (node) {
            Node *leftChild = node->left;
            if (leftChild != NULL && leftChild->left == NULL && leftChild->right == NULL) {
                count += 1;
            }
            leavesOfLeftChild(node->left, count);
            leavesOfLeftChild(node->right, count);
        }
    }
};

int main() {
    int ctrl;
    std::cin >> ctrl;

    while (ctrl--) {
        std::string string;
        std::cin >> string;
        class BiTree biTree;
        biTree.assign(string);
        std::cout << biTree.leavesOfLeftChild() << std::endl;
    }

    return 0;
}

评论