Binary Tree Recursive

1.Minimum Depth of Binary Tree

    // recursive version, the time complexity of O (n), the spatial complexity of O (logN) 
	Private static int minDepth (the TreeNode the root) { 
		IF (the root == null) return 0;   
		return Math.min (minDepth (root.left) , minDepth (root.right)) +. 1; 
	}

2.Maximum Depth of Binary Tree

Ibid., Recursive version, // time complexity of O (n), the spatial complexity of O (logN) 
public int maxDepth (the TreeNode the root) { 
    IF (the 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);// add deleted 
	}

5.Binary Tree Maximum Path Sum

    // time complexity of O (n), the spatial complexity of O (logN) 
    Private int max_sum; 
	Private int DFS (the TreeNode the root) { 
		IF (the root == null) return 0; 

		int L = DFS (root.left); 
		int DFS = R & lt (root.right); 

		int = SUM root.val; 
		IF (L> 0) = SUM + L; 
		IF (R & lt> 0) = SUM + R & lt; 

		max_sum Math.max = (SUM, max_sum); 
		return ? math.max (L, R & lt)> 0 math.max (L, R & lt) + root.val: root.val; 
	}

 

Guess you like

Origin www.cnblogs.com/rnanprince/p/11595176.html