Find Tree height (general iteration method)
1.Link
2. 题目描述
求给定二叉树的最大深度,最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。 示例1
输入
复制
返回值
复制
示例2
输入
复制
返回值
复制
3. 思路
bottom-up method:
每个node的input: node, ouput: max_depth of current node
如果node是none,return 0。否则从left, right children获取 max_depth values, 然后返回 Max(left depth, right depth) +1
top down method:
每个node的input: node, depth of parent ouput: None
用global的max_depth 存放结果
如果node是none,return, 否则 max_depth = max(max depth, depth + 1)
4.Coding
Recursion method
Iteration DFS method
Tree 的iteration general的方法/DFS + 每一层都有返回的写法
在原来的 iteration method for Tree traversal 的方法上添加以下两条
对于每一层的node的输入,可以在 stack append (node.left, cnt, other inputs)的tuple里面给 child node进行input的添加
对于每个node的返回值,可以用一个result stack存放子节点的返回值
在post-order 的地方进行返回操作, 如果current node 有right node就pop result stack的最后一个value,同理如果有left node,就pop最后一个value。 注意: 一定是先pop right再pop left,因为left的result是先比right的res 储存
简单来说, input 就是在cnt=0 或1的情况 stack.append()的tuple里面添加input。 而output就是在post-order里面从result stack里面pop值出来更新当前的node的result,再append进去返回。
Iteration BFS method/ Level order method
Last updated
Was this helpful?