路径/Path Sum

一步到位

  • Path Sum II

List:

  • Binary Tree Paths

  • path sum I, II, III, IV

  • sum root to leave numbers

  • sum of left leaves

  • binary tree maximum path sum

  • Longest Univalue path

  • Second Minimum Node In a Binary Tree

  • All Nodes Distance K in Binary Tree(好题)

  • 路径题的backtracking模板

  • 这题还需要注意"->"的处理

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null) return res;
        helper(root, res, new StringBuilder());
        return res;
    }
    private void helper(TreeNode root, List<String> res, StringBuilder sb){
        if(root == null){
            return;
        }
        int len = sb.length();
        sb.append(root.val);
        if(root.left == null && root.right == null){
            res.add(sb.toString());
        }else{
            sb.append("->");
            helper(root.left, res, sb);
            helper(root.right, res, sb);
        }
        sb.setLength(len);
    }
}

  • 判断root.left == null && root.right == null && sum - root.val == 0

  • 不用先求max depth

Path Sum II (好题)

  • backTracking入门好题

  • 找出所有的path which sum up to target

  • backtracking, DFS查找

  • 有加必有减

  • 即使找到了结果也不能直接return

  • 要等着把最后一个remove来判断是否还有其它满足条件的可能

  • 另一种 解法

  • 针对cur node需要判断三种情况

    • cur node is a child node-> check whether sum is equal to target

    • cur.left != null ->先加后减

    • cur.right != null -> 先加后减

Path Sum III

  • 找满足条件的sub path的个数,不一定从root开始,从leaf结束,但是必须是向下的一个subPath

  • 这题要干两件事

    • 计算从root开始到cur child node的path sum == target的cnt

    • 遍历每个node,以每个node为root都findPath( ),把结果累加上

  • 所以其实应该有一个findPathNumber的题目过渡下会更好

  • 只是recursion/ D&C, 不涉及backtracking

Path Sum IV

Sum root to leaf numbers

  • 做完Path Sum II之后发现这题跟那题思路一样

Sum of left leaves

  • 先找root.left这个点,不为空的话判断它是否是leaf node,如果是就把结果加上

  • 如果root.left不是leaf node, 就res += sumofLeftLeaves(root.left)

  • 然后判断root.right是否为空,如果不是,就res += sumofLeftLeaves(root.right)

  • 感觉这题的recursive的思路跟inOrderSuccessorof BST很像

  • 这题的Iterative的解法

  • 这题属于没做过很难想的题目

  • 因为treenode会包含负数

  • 借着建立public int maxSumSinglePath(TreeNode root, int[] max)和计算single path max sum ending with curnode

  • 来获得maximum path sum, max[0]

Longest Univalue Path

  • 套用max path sum的思路

  • 改进就是helper(TreeNode node, int val) 里把parent node.val传进来比较

Second minimum node in a Binary Tree

All Nodes Distance K in Binary Tree

  • 用一个hashmap来存储从root到target的path上的所有node, val存距离target的距离

  • 然后traverse tree, 如果遇到hashmap 里的node, 就用map.get(cur)的值来更新当前的距离

Last updated

Was this helpful?