左叶子之和
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null) return 0;
int result=0;
if(root.left!=null&&root.left.left==null&&root.left.right==null)
{
result=result+root.left.val;
}
return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right)+result;
}
}
树最左下角的值
class Solution {
public int findBottomLeftValue(TreeNode root) {
if(root==null) return 0;
int result=0;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty())
{
int t=queue.size();
TreeNode temp;
for(int i=0;i<t;i++)
{
temp=queue.poll();
if(i==0) result=temp.val;
if(temp.left!=null) queue.add(temp.left);
if(temp.right!=null) queue.add(temp.right);
}
}
return result;
}
}
最大二叉树
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return construct(nums,0,nums.length-1);
}
public TreeNode construct(int[] nums,int ns,int ne)
{
if(ns>ne) return null;
int index=ns;
int curroot=Integer.MIN_VALUE;
for(int i=ns;i<=ne;i++)
{
if(nums[i]>curroot)
{
curroot=Math.max(curroot,nums[i]);
index=i;
}
}
TreeNode root=new TreeNode(curroot);
root.left=construct(nums,ns,index-1);
root.right=construct(nums,index+1,ne);
return root;
}
}
合并二叉树
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1==null) return root2;
if(root2==null) return root1;
TreeNode root=new TreeNode(root1.val+root2.val);
root.left=mergeTrees(root1.left,root2.left);
root.right=mergeTrees(root1.right,root2.right);
return root;
}
}
二叉树搜索树中的搜素
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root==null) return null;
if(root.val<val)
{
return searchBST(root.right,val);
}
else if(root.val>val)
{
return searchBST(root.left,val);
}
else{
return root;
}
}
}