662. 二叉树最大宽度
思路:深搜时用哈希表记录每层的信息
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<Integer, Integer> map = new HashMap<>();
int max;
public int widthOfBinaryTree(TreeNode root) {
dfs(root, 0, 0);
return max;
}
void dfs(TreeNode u, int d, int x) {
if (u == null) return;
if (!map.containsKey(d)) {
map.put(d, x);
max = Math.max(max, 1);
} else {
max = Math.max(max, x - map.get(d) + 1);
}
dfs(u.left, d + 1, x * 2);
dfs(u.right, d + 1, x * 2 + 1);
}
}
779. 第K个语法符号
抽象成树形结构
每个节点的值与左节点的值相同,与右节点的值相反
从目标节点向上倒推至第一层
class Solution {
public int kthGrammar(int n, int k) {
int v = 1;
while (n > 1) {
int p = (k + 1) / 2;
if (k % 2 == 0)
v ^= 1;
k = p;
n--;
}
return v == 0 ? 1 : 0;
}
}