您的位置:首页 > 编程语言 > Go语言

Google Interview - Longest Continuous Path of Tree

2015-06-02 14:33 555 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/yuanhisn/article/details/84721993

给一个树root的pointer,树包含多个分支,树结构要自己创造。求一条最长路径。
例如(括号对应上面node)
树:                  2
      |            |            |                |
     5            7          3                 6
(|       | )( | )( | )        (|       |)
  6       3        2         4              5       8
                     |
                     3
返回3因为 (2-3-4) 这条线。优化要求时间O(n)

static class NTreeNode {
int val;
List<NTreeNode> children = new ArrayList<>();
}

public int longestContinuousPath(NTreeNode root) {
if(root == null) return 0;
return longestContinuousPath(root, 1);
}

public int longestContinuousPath(NTreeNode root, int len) {
int max = 0;
for(NTreeNode child:root.children) {
if(child == null) continue;
int curLen = longestContinuousPath(child, child.val == root.val + 1 ? len + 1 : 1);
max = Math.max(curLen, max);
}
return Math.max(max, len);
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: