71334
Posted 保护眼睛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了71334相关的知识,希望对你有一定的参考价值。
剑指 Offer 07. 重建二叉树
class Solution7 {
public int pIndex;
public TreeNode buildTreeChild(int[] preorder, int[] inorder, int begin, int end) {
if (begin > end)
return null;
TreeNode root = new TreeNode(preorder[pIndex]);
int index = getIndex(inorder, begin, end, preorder[pIndex]);
pIndex++;
root.left = buildTreeChild(preorder, inorder, begin, index - 1);
root.right = buildTreeChild(preorder, inorder, index + 1, end);
return root;
}
public int getIndex(int[] inorder, int begin, int end, int key) {
for (int i = begin; i <= end; i++) {
if (inorder[i] == key) {
return i;
}
}
return -1;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0)
return null;
return buildTreeChild(preorder, inorder, 0, inorder.length - 1);
}
}
剑指 Offer 13. 机器人的运动范围
class Solution13 {
public static void main(String[] args) {
System.out.println(movingCount(2, 3, 1));
}
static boolean[][] visited;
public static int movingCount(int m, int n, int k) {
visited = new boolean[m][n];
return dfs(0, 0, k, m, n);
}
private static int dfs(int i, int j, int k, int m, int n) {
if (i >= m || j >= n || getCountSum(i) + getCountSum(j) > k || visited[i][j]) {
return 0;
}
visited[i][j] = true;
return 1 + dfs(i + 1, j, k, m, n) + dfs(i, j + 1, k, m, n);
}
private static int getCountSum(int num) {
int sum = 0;
while (num != 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
}
剑指 Offer 34. 二叉树中和为某一值的路径
class Solution34 {
List<List<Integer>> res = new LinkedList<>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(root, target);
return res;
}
public void dfs(TreeNode root, int target) {
if (root == null)
return;
path.offer(root.val);
target -= root.val;
if (target == 0 && root.right == null && root.left == null) {
res.add(new LinkedList<>(path));
}
dfs(root.left, target);
dfs(root.right, target);
path.removeLast();
}
}
以上是关于71334的主要内容,如果未能解决你的问题,请参考以下文章