【算法第十五天7.29】513.找树左下角的值 112. 路径总和 106.从中序与后序遍历序列构造二叉树

链接力扣513-找树左下角的值

思路

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int res = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                if(i == 0) res = node.val;
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
        }
        return res;
    }
}

链接力扣112-路径总和

思路

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        // 用前序遍历
        if(root == null) return false;
        if(root.left == null && root.right == null) return targetSum == root.val;
        // 求两侧分支的路径和
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }
}

链接力扣106-从中序与后序遍历序列构造二叉树

思路

//  重点是:左闭右开的原则,以及子树长度
class Solution {
    Map<Integer,Integer> map;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++){
            map.put(inorder[i],i);
        }
        return 	getRoot(inorder,0,inorder.length,postorder,0,postorder.length);
    }
    public TreeNode getRoot(int[] inorder, int inStart,int inEnd,int[] postorder,int postStart,int postEnd){
        // 参数里的范围都是前闭后开,不是左闭右开,则无法返回树
        if(inStart >= inEnd || postStart >= postEnd) return null;
        // 获取中序中的根节点值;
        int index = map.get(postorder[postEnd - 1]);
        TreeNode root = new TreeNode(inorder[index]);
        // 求出左树的长度
        int lenOfLeft = index - inStart;
        // 根据左闭右开,来建立左子树、右子树
        root.left = getRoot(inorder,inStart,index, postorder,postStart,postStart + lenOfLeft);
        root.right = getRoot(inorder,index + 1, inEnd, postorder,postStart + lenOfLeft,postEnd - 1);
        // root.right = getRoot(inorder,index + 1, inEnd, postorder,postStart + index,postEnd - 1);
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值