1.从中序与后序遍历二叉树 106
看到这道题,想到的就是递归把整棵树化为左子树与右子树,但是需要不断地int出新数组,空间复杂度太高运行慢,还需要优化。copyOfRange(数组,左,右)方法要记住,左开右闭复制范围内的数组。
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
int m = inorder.length;
int n = postorder.length;
if (m == 0 || n == 0) return null;
int k = postorder[n - 1];
TreeNode root = new TreeNode(k);
for (int i = 0;i < m;i++) {
if (k == inorder[i]) {
k = i;
break;
}
}
int[] leftinorder = Arrays.copyOfRange(inorder,0,k);//复制,左闭右开
int[] leftpostorder = Arrays.copyOfRange(postorder,0,k);
root.left = buildTree(leftinorder,leftpostorder);
int[] rightinorder = Arrays.copyOfRange(inorder,k + 1,m);
int[] rightpostorder = Arrays.copyOfRange(postorder,k,n - 1);
root.right = buildTree(rightinorder,rightpostorder);
return root;
}
}
2.合并二叉树 617
简单的二叉树数值修改问题,构建新子树即可
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return root1 == null ? root2 : root1;
}
if (root1 == null && root2 == null) {
return null;
}
TreeNode root = new TreeNode(root1.val + root2.val);
root.left = mergeTrees(root1.left,root2.left);
root.right = mergeTrees(root1.right,root2.right);
return root;
}
}
3.最大二叉树 654
先构造一个线程,求的是一个序列里面的最大位置,返回的是位置的int类型参数
确定位置后,我们开始构造。创建构造线程,建立根节点是最长nums序列,然后建立左右子树,最后输出即可。
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return build(nums,0,nums.length);
}
public TreeNode build (int[] nums,int left,int right) {
if (left == right) return null;
int m = max(nums,left,right);
TreeNode root = new TreeNode(nums[m]);
root.left = build(nums,left,m);
root.right = build(nums,m + 1,right);
return root;
}
public int max(int[] nums,int left,int right) {
int k = left;
for (int i = left;i < right;i++) {
if (nums[i] > nums[k]) {
k = i;
}
}
return k;
}
}
4.二叉树的坡度,563
dfs的return总是返回不对,看了答案,思考为什么dfs要return节点总和呢?
class Solution {
int sum = 0;
public int findTilt(TreeNode root) {
dfs(root);
return sum;
}
public int dfs(TreeNode root) {
if (root == null) return 0;
int left = dfs(root.left);
int right = dfs(root.right);
sum = sum + Math.abs(left - right);
return left + right + root.val;
}
}