Given a tree, find the smallest subtree that contains all of the tree‘s deepest nodes.. from: 1point3acres.com/bbs
a
/ | \.
b c d/ \ |
e f g
/ / \.
h i j
depth of tree: 4
deepest nodes:[h,i,j]
least common ancestor of [h,i,j]: b.
return: b
我问面试官这个树的定义呢,我要不要写一写,面试官说不用了,你就随意写吧,我可以【猜】啊!
我就找到leetcode上面哪个lowest common ancestor of binary tree,一通瞎改了改改成了多叉树版本的,这时候我是直接使用了 h,i,j 这几个节点假设是输入的。
import java.util.ArrayList;
class TreeNode{
int val;
ArrayList<TreeNode> children;
public TreeNode(int val){
this.val = val;
children = new ArrayList<>();
}
}
class Result{
TreeNode node;
int maxDepth;
public Result(TreeNode node, int maxDepth){
this.node = node;
this.maxDepth = maxDepth;
}
}
public class Solution{
public static TreeNode find(TreeNode root){
if(root == null || root.children.isEmpty()) return root;
return helper(root).node;
}
public static Result helper(TreeNode root){
if(root.children.isEmpty()) return new Result(root, 1);
int size = root.children.size();
int maxDepth = Integer.MIN_VALUE;
Result r = new Result(root, maxDepth);
for(int i = 0; i < size; i++){
Result tmp = helper(root.children.get(i));
if(tmp.maxDepth > maxDepth){
maxDepth = tmp.maxDepth;
r.node = tmp.node;
r.maxDepth = tmp.maxDepth + 1;
}
else if(tmp.maxDepth == maxDepth){
r.node = root;
}
}
return r;
}
public static void main(String[] args){
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
TreeNode n6 = new TreeNode(6);
TreeNode n7 = new TreeNode(7);
TreeNode n8 = new TreeNode(8);
TreeNode n9 = new TreeNode(9);
TreeNode n10 = new TreeNode(10);
n1.children.add(n2);
n1.children.add(n3);
n1.children.add(n4);
n2.children.add(n5);
n2.children.add(n6);
n4.children.add(n7);
n5.children.add(n8);
n5.children.add(n9);
n6.children.add(n10);
TreeNode res = find(n1);
System.out.println(res.val);
}
}