DAY16

找树左下角的值

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值