二叉树的递归

1.Minimum Depth of Binary Tree

    // 递归版,时间复杂度O(n),空间复杂度O(logn)
	private static int minDepth(TreeNode root) {
		if (root == null)   return 0;  
		return Math.min(minDepth(root.left), minDepth(root.right))+1;
	}

2.Maximum Depth of Binary Tree

同上,递归版,// 时间复杂度O(n),空间复杂度O(logn)
public int maxDepth(TreeNode root) {
    if (root == null) return 0;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

3.Path Sum

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22
// 时间复杂度O(n),空间复杂度O(logn)
public boolean hasPathSum(TreeNode root, int sum) {
    if (root == null) return false;
    if (root.left == null && root.right == null) // leaf
        return sum == root.val;
    return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}

4.Path Sum II

        同上,返回路径  // 时间复杂度O(n),空间复杂度O(logn)
	public List<List<Integer>> pathSum(TreeNode root, int sum) {
		List<List<Integer>> result = new ArrayList<>();
		ArrayList<Integer> cur = new ArrayList<>(); // 中间结果
		pathSum(root, sum, cur, result);
		return result;
	}

	private static void pathSum(TreeNode root, int gap, ArrayList<Integer> cur, List<List<Integer>> result) {
		if (root == null)  return;
		cur.add(root.val);
		if (root.left == null && root.right == null) {
			if (gap == root.val) {  result.add(new ArrayList<>(cur)); }
		}
		pathSum(root.left, gap - root.val, cur, result);
		pathSum(root.right, gap - root.val, cur, result);
		cur.remove(cur.size() - 1);   //添加的删除了
	}

5.Binary Tree Maximum Path Sum

    // 时间复杂度O(n),空间复杂度O(logn)
    private int max_sum;
	private int dfs(TreeNode root) {
		if (root == null) return 0;

		int l = dfs(root.left);
		int r = dfs(root.right);

		int sum = root.val;
		if (l > 0) sum += l;
		if (r > 0) sum += r;

		max_sum = Math.max(sum, max_sum);
		return Math.max(l, r) > 0 ? Math.max(l, r) + root.val : root.val;
	}

猜你喜欢

转载自www.cnblogs.com/rnanprince/p/11595176.html