python求二叉树深度与宽度

如图所示二叉树:

import queue
class Node(object):
    def __init__(self, data=None, left=None, right=None):
        self.data = data
        self.right = right
        self.left = left
def tree_depth(tree):
    if tree == None:
        return 0
    else:
        return max(tree_depth(tree.left), tree_depth(tree.right)) + 1
def tree_width(tree):

    if tree == None:
        return 0
    else:
        q = queue.Queue()
        lis = []
        n = 1
        q.put(tree)
        winth = 0
        max_winth = 0
        while not q.empty():
            for i in range(n):
                temp = q.get()
                lis.append(temp.data)
                if temp.left:
                    q.put(temp.left)
                    winth += 1
                if temp.right:
                    q.put(temp.right)
                    winth += 1
            n = winth
            if max_winth < winth:
                max_winth = winth
            winth = 0
        return max_winth, lis

if __name__ == '__main__':
    tree = Node('D', Node('B', Node('A'), Node('C')), Node('E', right=Node('G', Node('F'))))
    print(tree_depth(tree))
    print(tree_width(tree))

加上lis 可以得到二叉树的层次遍历结果,用队列的性质。另外,queue还有LifoQueue,此时的队列相当于一个栈,后入先出。

每次get()其实相当于python里面的pop(),只不过pop()可以出任意位置的数,而get()只能是最先进的那个数,出去就相当于删去这个数了。

### 计算二叉树最大宽度的算法 #### BFS 实现方法 通过广度优先搜索(BFS),可以逐层遍历二叉树并计算每层的宽度。为了处理可能存在的 `null` 节点,可以通过给每个节点分配唯一的索引来解决此问题。具体来说,在父节点的基础上,左子节点的索引为 `parent_index * 2 + 1`,而右子节点的索引为 `parent_index * 2 + 2`。 以下是基于 Java 的实现代码: ```java import java.util.LinkedList; import java.util.Queue; class TreeNode { int val; TreeNode left, right; TreeNode(int x) { val = x; left = right = null; } } public class BinaryTreeWidthCalculator { public int widthOfBinaryTree(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); root.val = 0; // 初始化根节点的编号为 0 queue.offer(root); int maxWidth = 0; while (!queue.isEmpty()) { int levelSize = queue.size(); int firstIndex = queue.peek().val; int lastIndex = firstIndex; for (int i = 0; i < levelSize; i++) { TreeNode current = queue.poll(); lastIndex = current.val; if (current.left != null) { current.left.val = current.val * 2 + 1; queue.offer(current.left); } if (current.right != null) { current.right.val = current.val * 2 + 2; queue.offer(current.right); } } maxWidth = Math.max(maxWidth, lastIndex - firstIndex + 1); } return maxWidth; } } ``` 上述代码实现了 BFS 方法来计算二叉树的最大宽度[^4]。它利用队列存储当前层的节点及其对应的唯一索引值,并在每次迭代中更新最大宽度。 --- #### DFS 实现方法 除了 BFS 外,还可以使用深度优先搜索(DFS)递归地访问每一个节点,并记录其所在层数以及对应的位置索引。最终比较同一层中最左侧和最右侧节点的距离即可得到该层的宽度。 下面是 Python 版本的一个例子: ```python from collections import deque # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def widthOfBinaryTree(root: TreeNode) -> int: if not root: return 0 max_width = 0 queue = deque([(root, 0)]) # 存储节点其位置索引 while queue: _, start_idx = queue[0] level_size = len(queue) for _ in range(level_size): node, idx = queue.popleft() if node.left: queue.append((node.left, 2*idx)) if node.right: queue.append((node.right, 2*idx+1)) end_idx = idx max_width = max(max_width, end_idx - start_idx + 1) return max_width ``` 这段代码同样采用了层次遍历的方式,不过它是用双端队列代替了普通的列表作为辅助结构[^3]。 --- #### 时间空间复杂度分析 无论采用哪种方式解决问题的时间复杂度均为 O(n),其中 n 表示整个二叉树中的总节点数目;因为我们需要至少访问一次所有的节点才能完成任务。至于额外使用的内存大小,则取决于所选策略的不同:对于 BFS 来说可能是 O(w),w 是某一层上的最多节点数量;而对于 DFS 则接近于 O(h),h 即代表树的高度[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值