class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1==null)
return t2;
if(t2==null)
return t1;
TreeNode t3 = new TreeNode(t1.val + t2.val);
t3.left = mergeTrees(t1.left, t2.left);
t3.right = mergeTrees(t1.right, t2.right);
return t3;
}
}
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1==null)
return t2;
if(t2==null)
return t1;
t1.val = t1.val + t2.val;
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
return t1;
}
}
题解出处
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
int maxPos = maxPos(nums);
if(maxPos==-1)
return null;
int[] leftArray = Arrays.copyOfRange(nums, 0, maxPos);
int[] rightArray = Arrays.copyOfRange(nums, maxPos+1, nums.length);
TreeNode root = new TreeNode(nums[maxPos]);
root.left = constructMaximumBinaryTree(leftArray);
root.right = constructMaximumBinaryTree(rightArray);
return root;
}
public int maxPos(int[] nums){
if(nums.length==0)
return -1;
int pos = -1;
int max = nums[0];
for(int i=0; i<nums.length; i++){
if(nums[i]>=max){
pos = i;
max = nums[i];
}
}
return pos;
}
}
题解出处
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root==null) return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.val==0 && root.left==null && root.right==null)
root = null;
return root;
}
}
题解出处
class Solution {
TreeNode last = null;
public void flatten(TreeNode root) {
if(root==null) return;
if(last!=null){
last.left = null;
last.right = root;
}
last = root;
TreeNode copyRight = root.right;
flatten(root.left);
flatten(copyRight);
}
}