class Solution {
int[] preorder;
HashMap<Integer, Integer> dic = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
for(int i = 0; i < inorder.length; i++)
dic.put(inorder[i], i);//由根节点值直接找到中序索引,免去二次查询
return recur(0, 0, inorder.length - 1);
}
TreeNode recur(int root, int left, int right) {
if(left > right) return null;
TreeNode node = new TreeNode(preorder[root]);
int i = dic.get(preorder[root]);// 划分根节点、左子树、右子树
node.left = recur(root + 1, left, i - 1);
node.right = recur(root + i - left + 1, i + 1, right);
return node;
}
}
Deque<String> deque = new LinkedList<>();
deque.offerLast("A"); // A
void backtracking(参数) {
if (结束遍历条件) {
存放结果;return;
}
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
if (!isValid(..)) continue;//// 排除不合法选择
进行回溯预备处理;
backtracking(路径,选择列表); // 深入
恢复现场;
}
}
int BFS(Node start, Node target) {
Queue<Node> q;
Set<Node> visited; // 避免走回头路,有替代方案
q.offer(start); // 将起点加入队列
visited.add(start);
int step = 0;
while (!q.isEmpty()) {//while:向下
int sz = q.size();
for (int i = 0; i < sz; i++) {//for:遍历该层
Node cur = q.poll();
//注意:此处可进行节点处理
if (达成目标) return step;
for (Node x : cur.adj()) { //否则将cur的相邻节点加入队列
if (!visited(x)) {
q.offer(x);
visited.add(x);
}
}
}
step++;//更新步数,在下一个元素出队之前
}
}
/*通过(x-1) (x+1)操作最右特定位
x - 1: 原最右的“1”变为“0”,最右边的“0”们变成“1”,
x + 1: 最右边的“1”们变成“0”,原最右的“0”变成“1”;0xFFFF->0x10000
*/
//使用&,意味着“0化”,改变原先的“1”,原先的“0”不变
x & (x - 1) //最右边的“1”置为“0”,值为0说明x只含一位“1”,为2的幂
x & (x + 1) //最右边的“1”们置为“0”, 值为0说明x类似于0b00..0011..11,即2^n - 1
//使用|,意味着“1化”,似上,原先的“1”不变
x | (x - 1) //最右边的“0”们置为“1”
x | (x + 1) //最右边的“0”置为“1”
//使用^,进行分化
x ^ (x - 1) //对最右边的“1”的右边“0”们都置“1”,其左边的位均置“0”
x ^ (x + 1) //对最右的“0”置为“1”,其左边的位均置“0”.
/* ~x:翻转位,运算符操作同上 */
~x & (x - 1) //最右边的“0”们变成“1”,其余位置“0”
~x & (x + 1) //最右边的“0”变成“1”,其余位置“0”
~x | (x - 1) //最右边的“1”变成“0”,并其余位置“1”
~x | (x + 1) //最右边的“1”们变成“0”,并将其余位置“1”
x & (-x) //获取最右侧位,因为 -x == ~x + 1
int low = 0, fast = 0;
while (fast < nums.size()) {
if (nums[fast] & 1) {
swap(nums[low], nums[fast]);
low ++;
}
fast++;
}
public boolean isSubStructure(TreeNode A, TreeNode B) {
if (B == null || A == null) return false;
return Match(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
}
private boolean Match(TreeNode A, TreeNode B){
if (B == null) return true;
if (A == null || A.val != B.val) return false;
return Match(A.left,B.left) && Match(A.right,B.right);
}