找树左下角的值
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> q=new LinkedList<>();
if(root==null)return 0;
int res=0;
q.offer(root);
while(!q.isEmpty()){
int len=q.size();
for(int i=0;i<len;i++){
TreeNode t=q.poll();
if(i==0)res=t.val;
if(t.left!=null)q.offer(t.left);
if(t.right!=null)q.offer(t.right);
}
}
return res;
}
路径总和I
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null)return false;
if(root.left==null&&root.right==null&&root.val==targetSum)return true;
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
路径总和II
List<List<Integer>> res=new ArrayList<>();
List<Integer> path=new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if (root == null) return res;
getPath(root,targetSum);
return res;
}
public void getPath(TreeNode root, int targetSum){
path.add(root.val);
if(root.left==null&&root.right==null){
if(root.val==targetSum){
res.add(new ArrayList<>(path));
}
return;
}
if(root.left!=null){
getPath(root.left,targetSum - root.val);
path.remove(path.size()-1);
}
if(root.right!=null){
getPath(root.right,targetSum - root.val);
path.remove(path.size()-1);
}
}
从中序与后序遍历序列构造二叉树
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return buildBBTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
public TreeNode buildBBTree(int[] inorder, int[] postorder,int ibegin,int iend,int pbegin,int pend){
if(ibegin>iend||pbegin>pend)return null;
TreeNode root=new TreeNode(postorder[pend]);
int index=0;
for(int i=ibegin;i<=iend;i++){
if(inorder[i]==postorder[pend]){
index=i;
break;
}
}
int len=index-ibegin;
root.left=buildBBTree(inorder,postorder,ibegin,index-1,pbegin,pbegin+len-1);
root.right=buildBBTree(inorder,postorder,index+1,iend,pbegin+len,pend-1);
return root;
}
}