【代码随想录训练营】Day18-二叉树

代码随想录训练营 Day18

今日任务

513.找树左下角的值
112.路径总和
113.路径总和Ⅱ
106.从中序与后序遍历序列构造二叉树
105.从前序与中序遍历序列构造二叉树
语言:Java

513. 找树左下角的值

链接:https://leetcode.cn/problems/find-bottom-left-tree-value/
递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int result;
    int maxDepth;
    //递归:深度最深的叶子节点中最左边的
    public void maxDepth(TreeNode root, int depth){
        //叶子节点
        if(root.left == null && root.right == null){
            //被result记录的一定是每层最左边的元素
            if(depth > maxDepth){
                maxDepth = depth;
                result = root.val;
            }
            return;
        }
        if(root.left != null){
            // //显式回溯
            // depth++;
            // maxDepth(root.left, depth);
            // depth--;
            maxDepth(root.left, depth + 1); //隐式回溯
        }
        if(root.right != null){
            maxDepth(root.right, depth + 1);
        }
    }
    public int findBottomLeftValue(TreeNode root) {
        maxDepth(root, 1);
        return result;
    }
}

迭代(层序遍历)

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

112. 路径总和

链接:https://leetcode.cn/problems/path-sum/
递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int flag; //用于标记是否已找到路径
    public void getSum(TreeNode root, int targetSum){
        int curSum = 0;
        curSum += root.val; //根
        if(root.left == null && root.right == null && curSum == targetSum){
            flag = 1;
            return;
        }
        if(root.left != null){
            //隐式回溯
            getSum(root.left, targetSum - curSum); //左
        }
        if(root.right != null){
            getSum(root.right, targetSum - curSum); //右
        }
    }
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null){
            return false;
        }
        flag = 0;
        getSum(root, targetSum);
        if(flag == 1){
            return true;
        }
        return false;
    }
}

迭代(两个栈)

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null){
            return false;
        }
        //<节点,当前和>
        //Stack<Pair<TreeNode, Integer>> stack = new Stack<Pair<TreeNode, Integer>>();
        Stack<TreeNode> nodeST = new Stack<TreeNode>();
        Stack<Integer> intST = new Stack<Integer>();
        nodeST.push(root);
        intST.push(root.val);
        while(!nodeST.isEmpty()){
            TreeNode curNode = nodeST.pop();
            int curSum = intST.pop();
            if(curNode.left == null && curNode.right == null && curSum == targetSum){
                return true;
            }
            if(curNode.left != null){
                nodeST.push(curNode.left);
                intST.push(curNode.left.val + curSum);
            }
            if(curNode.right != null){
                nodeST.push(curNode.right);
                intST.push(curNode.right.val + curSum);
            }
        }
        return false;
    }
}

113. 路径总和Ⅱ

链接:https://leetcode.cn/problems/path-sum-ii/
递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<List<Integer>> result;
    List<Integer> curPath;
    public void getPath(TreeNode root, List<Integer> curPath, int targetSum){
        int curSum = 0;
        curSum += root.val;
        curPath.add(root.val);
        if(root.left == null && root.right == null && curSum == targetSum){
            //这里不可以写成 add(curPath)
            //因为Java传入的是引用,curPath里的内容一直在变
            //变到最后curPath中只有根节点了
            //必须新建一个不会变的对象add进去
            //result.add(curPath); //[[5],[5]]
            result.add(new ArrayList<>(curPath));
        }
        if(root.left != null){
            //隐式回溯
            getPath(root.left, curPath, targetSum - curSum);
            curPath.remove(curPath.size() - 1); //下一层递归时加了元素进去,回到上一层后要弹出来
        }
        if(root.right != null){
            //隐式回溯
            getPath(root.right, curPath, targetSum - curSum);
            curPath.remove(curPath.size() - 1);
        }
    }
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        result = new ArrayList<List<Integer>>();
        if(root == null){
            return result;
        }
        curPath = new ArrayList<Integer>();
        getPath(root, curPath, targetSum);
        return result;
    }
}

106. 从中序与后序遍历序列构造二叉树

链接:https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    //unique values,利用这个条件
    //<值, 位置>
    Map<Integer, Integer> map;
    //左闭右闭
    public TreeNode findRoot(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd){
        if(inBegin > inEnd || postBegin > postEnd){
            return null;
        }
        int rootIndex = map.get(postorder[postEnd]);
        TreeNode root = new TreeNode(postorder[postEnd]);
        root.left = findRoot(inorder, inBegin, rootIndex - 1, postorder, postBegin, postBegin + rootIndex - inBegin - 1);
        root.right = findRoot(inorder, rootIndex + 1, inEnd, postorder, postBegin + rootIndex - inBegin, postEnd - 1);
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++){
            map.put(inorder[i], i);
        }
        return findRoot(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }
}

105. 从前序与中序遍历序列构造二叉树

链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    Map<Integer, Integer> map;
    public TreeNode findRoot(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd){
        //rootIndex一直在改变
        //left:preEnd和inEnd受rootIndex影响
        //right:preBegin和inBegin受rootIndex影响
        //所以会有下标不符合逻辑的情形
        if(preBegin > preEnd || inBegin > inEnd){
            return null;
        }
        int rootIndex = map.get(preorder[preBegin]);
        TreeNode root = new TreeNode(preorder[preBegin]);
        //最好还是单独表示下左子树的长度,不然传入参数时总是忘记要减inBegin
        root.left = findRoot(preorder, preBegin + 1, preBegin + rootIndex - inBegin, inorder, inBegin, rootIndex - 1);
        root.right = findRoot(preorder, preBegin + rootIndex - inBegin + 1, preEnd, inorder, rootIndex + 1, inEnd);
        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++){
            map.put(inorder[i], i);
        }
        return findRoot(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值