代码随想录算法训练营第十八天|513.找树左下角的值、112. 路径总和、113.路径总和ii、106.从中序与后序遍历序列构造二叉树、105.从前序与中序遍历序列构造二叉树

513.找树左下角的值

513. 找树左下角的值 - 力扣(LeetCode)
使用前序遍历,存储叶子节点的值,当新的叶子节点深度大于原来叶子节点深度时,再更新value,因为是先遍历左节点,又因为deep>Deep时再更新,所以同一层不会更新,一直存储的都是深度最大且在左边的元素

class Solution {
    //最大节点深度
    private int Deep = 0;
    //节点最左侧值
    private int value;
    public int findBottomLeftValue(TreeNode root) {
        findLeftValue(root, 1);
        return value;
    }

    private void findLeftValue(TreeNode node, int deep) {
        if (node == null) {
            return;
        }
        if (node.left == null && node.right == null) {
            //deep大于当前最大Deep时才会更新,所以同一深度的存储的是左节点,因为先遍历的左节点
            if (deep > Deep) {
                value = node.val;
                Deep = deep;
            }
        }
        if (node.left != null) {
            findLeftValue(node.left, deep+1);
        }
        if (node.right != null) {
            findLeftValue(node.right, deep+1);
        }
    }
}

112. 路径总和

112. 路径总和 - 力扣(LeetCode)
本题判断是否存在和为指定值的路径,那么只需要判断即可,比较容易

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        targetSum -= root.val;
        if (root.left == null && root.right == null) {
            return targetSum == 0;
        }
        if (root.left != null) {
            boolean left = hasPathSum(root.left, targetSum);
            if (left) {
                return true;
            }
        }
        if (root.right != null) {
            boolean right = hasPathSum(root.right, targetSum);
            if (right) {
                return right;
            }
        }
        return false;
    }
}

113.路径总和ii

113. 路径总和 II - 力扣(LeetCode)
本题和112不同的是需要找出特定的路径,与257. 二叉树的所有路径类似,但是要注意的是res不能直接add path,因为path后面会变,所以需要新建一个加入

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        List<Integer> paths = new ArrayList<>();
        traversal(root,targetSum,paths,res);
        return res;
    }
    private void traversal(TreeNode node, int targetSum, List<Integer> paths, List<List<Integer>> res) {
        paths.add(node.val);
        // 叶子节点处理
        if (node.left == null && node.right == null) {
            if (targetSum == node.val) {
                // 后续paths会改变,所以需要定义一个新的列表
                res.add(new ArrayList<>(paths));
            }
            return;
        }
        if (node.left != null) {
            traversal(node.left, targetSum-node.val, paths, res);
            paths.remove(paths.size()-1);
        }
        if (node.right != null) {
            traversal(node.right, targetSum-node.val, paths, res);
            paths.remove(paths.size()-1);
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容