二叉树

二叉树的遍历
反转二叉树
合并二叉树
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;
}
}
654. 最大二叉树

题解出处

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;
}
}
814. 二叉树剪枝

题解出处

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;
}
}
114. 二叉树展开为链表

题解出处

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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值