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); }
相关文章推荐
- geeksforgeeks Find the maximum path sum between two leaves of a binary tree
- Minimum Path Sum of a Binary Tree
- leetcode -day17 Path Sum I II & Flatten Binary Tree to Linked List & Minimum Depth of Binary Tree
- [124]. Binary Tree Maximum Path Sum, [543]. Diameter of Binary Tree
- return longest tree path from root to leaf
- the longest distance of a binary tree
- Leetcode: mimimum depth of tree, path sum, path sum II
- 【SPOJ-PT07Z】Longest path in a tree【DFS/BFS】【树的直径】
- SPOJ Problem 1437:Longest path in a tree
- longest continuous subsequence of 0s
- Tree Longest Path With Same Value -LintCode
- FB面经Prepare: Find Longest Path in a Multi-Tree
- SPOJ 1437 Longest path in a tree
- 树直径、二叉树直径 Tree diameter (Longest path in an undirected tree)
- K-D tree HDU 2966 In case of failure
- Minimum Depth of Binary Tree(二叉树DFS)
- Minimum Depth of Binary Tree
- LeetCode--No.111--Minimum Depth of Binary Tree
- Lowest Common Ancestor of a Binary Search Tree
- [leetcode]Binary Tree Maximum Path Sum