题目地址:
https://www.lintcode.com/problem/1129/
给定一棵二叉树,求其一棵子树,该子树包含了所有该二叉树的最深的节点。返回其根。
思路是DFS。先递归求解左右子树,返回左右子树的包含该子树的最深节点的树根,以及左右子树各自的深度,如果两个都是null,则说明当前是叶子,则返回当前节点及其深度;如果一个是null,则返回另一个;如果都不是null,则看深度,如果两者不一样深,则返回更深的那个;如果一样深,则说明当前树根是含所有最深节点的子树根,则返回当前树根及当前子树最深深度。代码如下:
public class Solution {
class Pair {
TreeNode node;
int depth;
public Pair(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
/**
* @param root: a binary tree.
* @return: return the minimun subtree contains all the key nodes.
*/
public TreeNode subtreeWithAllKeyNodes(TreeNode root) {
// write your code here.
return dfs(root, 0).node;
}
private Pair dfs(TreeNode cur, int depth) {
if (cur == null) {
return null;
}
Pair left = dfs(cur.left, depth + 1), right = dfs(cur.right, depth + 1);
if (left == null && right == null) {
return new Pair(cur, depth);
} else if (left == null) {
return right;
} else if (right == null) {
return left;
} else {
if (left.depth > right.depth) {
return left;
} else if (left.depth < right.depth) {
return right;
} else {
left.node = cur;
return left;
}
}
}
}
class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
}
}
时空复杂度 O ( n ) O(n) O(n)。