Python实现: 现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度

题目描述

现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度

输入描述:

输入的第一行表示节点的个数n(1 ≤ n ≤ 1000,节点的编号为0到n-1)组成,
下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号

输出描述:

输出树的高度,为一个整数

示例1

输入

5 
0 1 
0 2 
1 3 
1 4

输出

3

采用python实现

首先根据输入构建完成二叉树

同时由于我们不确定根节点是什么,要加入根节点判定

然后从根节点出发,采用深度遍历方法找到树的深度

代码:

class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.left_child = None
        self.right_child = None
        self.parent = None

    def __repr__(self):
        return self.key

    def __str__(self):
        return self.key

    def insert_node(self, newNode):
        if self.left_child == None:
            self.left_child = newNode
        else:
            self.right_child = newNode
    def tree_depth(self, tree_head):
        if not(tree_head):
            return 0
        else:
            nleft = self.tree_depth(tree_head.left_child)
            nright = self.tree_depth(tree_head.right_child)
            return max(nleft + 1, nright + 1)


def find_tree_depth():
    n = input()
    if n == '':
        print('')
        return
    
    n = int(n)
    if n == 1:
        print(1)
        return 
    dic = {}
    head = []
    for i in range(0, n-1):
        nums = input().strip().split()
        if nums[0] in dic.keys():
            if nums[1] in dic.keys():
                dic[nums[0]].insert_node(dic[nums[1]])
            else:
                dic[nums[1]] = BinaryTree(nums[1])
                dic[nums[0]].insert_node(dic[nums[1]])

        else:
            q = BinaryTree(nums[0])
            dic[nums[0]] = q
            if nums[1] in dic.keys():
                dic[nums[0]].insert_node(dic[nums[1]])
            else:
                dic[nums[1]] = BinaryTree(nums[1])
                dic[nums[0]].insert_node(dic[nums[1]])

        dic[nums[1]].parent = dic[nums[0]]

        if dic[nums[0]].parent == None:
            if not nums[0] in head:
                head.append(nums[0])

        if nums[1] in head:
            head.remove(nums[1])


    print(head)
    print(dic[head[0]])
    print(dic[head[0]].left_child)
    print(dic[head[0]].right_child)
    p = dic[head[0]]
    # j = 1
    j = p.tree_depth(p)
    print(j)


find_tree_depth()

提交代码发现测试通过20%,测试用例:
291 0 1 0 2 0 3 0 4 2 5 4 6 3 7 7 8 6 9 4 10 9 11 0 12 5 13 5 14 14 15 11 16 0 17 6 18 9 19 13 20 8 21 13 22 15 23 21 24 9 25 17 26 18 27 27 28 26 29 27 30 19 31 4 32 31 33 11 34 10 35 7 36 27 37 22 38 16 39 12 40 24 41 12 42 32 43 2 44 14 45 14 46 6 47 18 48 1 49 12 50 22 51 13 52 15 53 53 54 54 55 53 56 18 57 42 58 25 59 21 60 44 61 7 62 7 63 30 64 64 65 12 66 9 67 42 68 13 69 47 70 34 71 53 72 25 73 26 74 30 75 7 76 51 77 70 78 70 79 8 80 26 81 43 82 41 83 41 84 79 85 58 86 72 87 25 88 57 89 36 90 56 91 40 92 13 93 63 94 6 95 12 96 23 97 17 98 93 99 59 100 67 101 2 102 19 103 93 104 20 105 53 106 55 107 8 108 54 109 83 110 64 111 75 112 25 113 17 114 83 115 84 116 116 117 46 118 62 119 10 120 63 121 23 122 58 123 31 124 92 125 75 126 57 127 31 128 102 129 123 130 129 131 92 132 2 133 128 134 134 135 6 136 130 137 43 138 136 139 68 140 72 141 95 142 32 143 27 144 87 145 10 146 83 147 22 148 71 149 90 150 43 151 71 152 77 153 114 154 50 155 43 156 116 157 20 158 30 159 104 160 149 161 4 162 20 163 111 164 125 165 17 166 92 167 147 168 14 169 4 170 51 171 40 172 117 173 83 174 164 175 118 176 72 177 86 178 120 179 81 180 2 181 116 182 73 183 20 184 143 185 183 186 154 187 126 188 124 189 100 190 8 191 52 192 38 193 32 194 12 195 17 196 171 197 113 198 112 199 142 200 92 201 59 202 119 203 153 204 29 205 33 206 28 207 96 208 97 209 201 210 121 211 12 212 156 213 62 214 204 215 181 216 150 217 104 218 111 219 180 220 69 221 145 222 70 223 214 224 79 225 142 226 14 227 97 228 56 229 60 230 103 231 82 232 181 233 59 234 82 235 59 236 13 237 43 238 31 239 167 240 195 241 28 242 142 243 12 244 27 245 143 246 241 247 3 248 188 249 113 250 128 251 224 252 163 253 206 254 224 255 158 256 156 257 168 258 192 259 218 260 229 261 17 262 233 263 251 264 242 265 174 266 20 267 56 268 194 269 52 270 162 271 269 272 104 273 228 274 79 275 222 276 57 277 131 278 218 279 245 280 167 281 173 282 107 283 239 284 172 285 284 286 233 287 252 288 238 289 95 290
对应输出应该为:
10
你的输出为:
6

可以发现0节点后面跟了6个节点,所以我觉得应该问题出现在“合法的二叉树”上面,是不是代码要将节点表示为链表的形式呢,测试如下:

class BinaryTree:
    def __init__(self, rootObj):
        self.key = rootObj
        self.child = None
        # self.right_child = None
        self.parent = None
        self.next = None

    def __repr__(self):
        return self.key

    def __str__(self):
        return self.key

    def insert_node(self, new_node):
        p = self.child
        if p:
            while p.next:
                p = p.next
            p.next = new_node

        else:
            self.child = new_node

    def tree_depth(self):
        if not (self.child):
            return 1
        else:
            max_depth = 0
            p = self.child
            while p:
                max_depth = max(max_depth, p.tree_depth() + 1)
                p = p.next
        return max_depth


def find_tree_depth():
    n = input()
    if n == '':
        print('')
        return

    n = int(n)
    if n == 1:
        print(1)
        return
    dic = {}
    head = []
    for i in range(0, n-1):
        nums = input().strip().split()
        if nums[0] in dic.keys():
            if nums[1] in dic.keys():
                dic[nums[0]].insert_node(dic[nums[1]])
            else:
                dic[nums[1]] = BinaryTree(nums[1])
                dic[nums[0]].insert_node(dic[nums[1]])

        else:
            q = BinaryTree(nums[0])
            dic[nums[0]] = q
            if nums[1] in dic.keys():
                dic[nums[0]].insert_node(dic[nums[1]])
            else:
                dic[nums[1]] = BinaryTree(nums[1])
                dic[nums[0]].insert_node(dic[nums[1]])

        dic[nums[1]].parent = dic[nums[0]]
        if dic[nums[0]].parent == None:
            if not nums[0] in head:
                head.append(nums[0])
        # else:
        #     if nums[0] in head:
        #         head.remove(nums[0])
        if nums[1] in head:
            head.remove(nums[1])
    # print(head)
    # print(dic[head[0]])
    # print(dic[head[0]].left_child)
    # print(dic[head[0]].right_child)
    p = dic[head[0]]
    # p = dic['1']
    # j = 1
    j = p.tree_depth()
    print(j)

find_tree_depth()

不通过

您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例
case通过率为50.00%

291 0 1 0 2 0 3 0 4 2 5 4 6 3 7 7 8 6 9 4 10 9 11 0 12 5 13 5 14 14 15 11 16 0 17 6 18 9 19 13 20 8 21 13 22 15 23 21 24 9 25 17 26 18 27 27 28 26 29 27 30 19 31 4 32 31 33 11 34 10 35 7 36 27 37 22 38 16 39 12 40 24 41 12 42 32 43 2 44 14 45 14 46 6 47 18 48 1 49 12 50 22 51 13 52 15 53 53 54 54 55 53 56 18 57 42 58 25 59 21 60 44 61 7 62 7 63 30 64 64 65 12 66 9 67 42 68 13 69 47 70 34 71 53 72 25 73 26 74 30 75 7 76 51 77 70 78 70 79 8 80 26 81 43 82 41 83 41 84 79 85 58 86 72 87 25 88 57 89 36 90 56 91 40 92 13 93 63 94 6 95 12 96 23 97 17 98 93 99 59 100 67 101 2 102 19 103 93 104 20 105 53 106 55 107 8 108 54 109 83 110 64 111 75 112 25 113 17 114 83 115 84 116 116 117 46 118 62 119 10 120 63 121 23 122 58 123 31 124 92 125 75 126 57 127 31 128 102 129 123 130 129 131 92 132 2 133 128 134 134 135 6 136 130 137 43 138 136 139 68 140 72 141 95 142 32 143 27 144 87 145 10 146 83 147 22 148 71 149 90 150 43 151 71 152 77 153 114 154 50 155 43 156 116 157 20 158 30 159 104 160 149 161 4 162 20 163 111 164 125 165 17 166 92 167 147 168 14 169 4 170 51 171 40 172 117 173 83 174 164 175 118 176 72 177 86 178 120 179 81 180 2 181 116 182 73 183 20 184 143 185 183 186 154 187 126 188 124 189 100 190 8 191 52 192 38 193 32 194 12 195 17 196 171 197 113 198 112 199 142 200 92 201 59 202 119 203 153 204 29 205 33 206 28 207 96 208 97 209 201 210 121 211 12 212 156 213 62 214 204 215 181 216 150 217 104 218 111 219 180 220 69 221 145 222 70 223 214 224 79 225 142 226 14 227 97 228 56 229 60 230 103 231 82 232 181 233 59 234 82 235 59 236 13 237 43 238 31 239 167 240 195 241 28 242 142 243 12 244 27 245 143 246 241 247 3 248 188 249 113 250 128 251 224 252 163 253 206 254 224 255 158 256 156 257 168 258 192 259 218 260 229 261 17 262 233 263 251 264 242 265 174 266 20 267 56 268 194 269 52 270 162 271 269 272 104 273 228 274 79 275 222 276 57 277 131 278 218 279 245 280 167 281 173 282 107 283 239 284 172 285 284 286 233 287 252 288 238 289 95 290
对应输出应该为:
10
你的输出为:
12

将测试用例的树打印出来:

的确存在这样长度 为12的一条路径,还是得不到哪里的问题

换用一种发放测试:

def find_tree_depth():
    n = input()
    if n == '':
        print('')
        return

    n = int(n)
    if n < 3:
        print(n)
        return

    len_array = [0] * n
    max_len = 0
    for i in range(0, n - 1):
        nums = input().strip().split()
        nums[0] = int(nums[0])
        nums[1] = int(nums[1])
        if len_array[int(nums[0])] == 0:
            len_array[int(nums[0])] = 1
        len_array[int(nums[1])] = len_array[int(nums[0])] + 1
        max_len = max(max_len, len_array[int(nums[1])])
    print(max_len)
    
find_tree_depth()

该方法默认输入顺序是从根节点开始的,才能完成,如果出现杂序,是不会通过的。

不通过

您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例
case通过率为50.00%

还是上面的测试用例不通过,有些没有办法了。。。。。。

看了一下论坛,找到一个可以通过测试的方法:

def find_tree_depth():
    n = input()
    if n == '':
        print('')
        return

    n = int(n)
    if n < 3:
        print(n)
        return

    len_array = [0] * n
    height = [0] * n
    max_len = 0
    height[0] = 1
    for i in range(0, n - 1):
        nums = input().strip().split()
        nums[0] = int(nums[0])
        nums[1] = int(nums[1])
        len_array[int(nums[0])] += 1
        if len_array[int(nums[0])] < 3:
            height[int(nums[1])] = height[int(nums[0])] + 1
        max_len = max(max_len, height[int(nums[1])])
    print(max_len)
    
find_tree_depth()

首先这个还是默认所有的顺序都是按照树的结构从上往下顺序输入,但是如果出现多余二叉的情况,直接就忽略了,这应该就是我们一直出错的地方所在了。因此我们把二叉代码也做相应的修改:


class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.left_child = None
        self.right_child = None
        self.parent = None

    def __repr__(self):
        return self.key

    def __str__(self):
        return self.key

    def insert_node(self, newNode):
        if self.left_child == None:
            self.left_child = newNode
        elif self.right_child == None:
            self.right_child = newNode
    def tree_depth(self, tree_head):
        if not(tree_head):
            return 0
        else:
            nleft = self.tree_depth(tree_head.left_child)
            nright = self.tree_depth(tree_head.right_child)
            return max(nleft + 1, nright + 1)
# def tree_depth(tree_head):
#     if
#     pass

def find_tree_depth():
    n = input()
    if n == '':
        print('')
        return

    n = int(n)
    if n == 1:
        print(1)
        return
    dic = {}
    head = []
    for i in range(0, n-1):
        nums = input().strip().split()
        if nums[0] in dic.keys():
            if nums[1] in dic.keys():
                dic[nums[0]].insert_node(dic[nums[1]])
            else:
                dic[nums[1]] = BinaryTree(nums[1])
                dic[nums[0]].insert_node(dic[nums[1]])

        else:
            q = BinaryTree(nums[0])
            dic[nums[0]] = q
            if nums[1] in dic.keys():
                dic[nums[0]].insert_node(dic[nums[1]])
            else:
                dic[nums[1]] = BinaryTree(nums[1])
                dic[nums[0]].insert_node(dic[nums[1]])

        dic[nums[1]].parent = dic[nums[0]]
        if dic[nums[0]].parent == None:
            if not nums[0] in head:
                head.append(nums[0])
        # else:
        #     if nums[0] in head:
        #         head.remove(nums[0])
        if nums[1] in head:
            head.remove(nums[1])
    # print(head)
    # print(dic[head[0]])
    # print(dic[head[0]].left_child)
    # print(dic[head[0]].right_child)
    p = dic[head[0]]
    # j = 1
    j = p.tree_depth(p)
    print(j)


find_tree_depth()

测试竟然完全通过了,所以问题就出在了“合法二叉树”上了,如果分支过多,这个直接就不要了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值