leetcode-maximum-width-of-binary-tree

题目大意

  https://leetcode.com/contest/leetcode-weekly-contest-46/problems/maximum-width-of-binary-tree/

  求树的同层横向最大距离。

题目分析

  思路参考了 https://discuss.leetcode.com/topic/100149/c-java-clean-code-with-explanation

  利用DFS计算,要为每个节点引入id(类似于二叉树用数组存储的思路,id的节点左右子节点存放在2 * id2 * id + 1位置),方便后续计算距离。

代码

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int ans;
private void dfs(TreeNode cur, int level, int idx, List<Integer> leftIds) {
if (cur == null) {
return;
}
if (leftIds.size() == level) {
leftIds.add(idx);
}
ans = Math.max(ans, idx - leftIds.get(level) + 1);
dfs(cur.left, level + 1, idx * 2, leftIds);
dfs(cur.right, level + 1, idx * 2 + 1, leftIds);
}
public int widthOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
ans = 1;
List<Integer> leftIds = new ArrayList<>();
dfs(root, 0, 1, leftIds);
return ans;
}
}

  时间复杂度:O(n),空间复杂度:o(h)