https://gist.github.com/gcrfelix/4ebb4b8c8b8c894d38a7
多叉树,每个节点是一个整数,求树中最长递增路径比如5,6,7,8,9
public class Solution {
int longest = 0;
public int findLongestPath(TreeNode root) {
if(root == null) {
return 0;
}
if(root.children == null || root.children.size() == 0) {
return 1;
}
longest = 1;
for(int i=0; i<root.children.size(); i++) {
findLongestPath(root.children.get(i), root.val, 1);
}
return longest;
}
public void findLongestPath(TreeNode root, int pre, int len) {
if(root == null) {
longest = Math.max(len, longest);
return;
}
if(root.children == null || root.children.size() == 0) {
longest = Math.max(len+1, longest);
return;
}
if(root.val > pre) {
for(int i=0; i<root.children.size(); i++) {
findLongestPath(root.children.get(i), root.val, len+1);
}
} else {
for(int i=0; i<root.children.size(); i++) {
findLongestPath(root.children.get(i), root.val, 1);
}
}
}
}
多叉树,每个节点是一个整数,求树中最长递增路径比如5,6,7,8,9
public class Solution {
int longest = 0;
public int findLongestPath(TreeNode root) {
if(root == null) {
return 0;
}
if(root.children == null || root.children.size() == 0) {
return 1;
}
longest = 1;
for(int i=0; i<root.children.size(); i++) {
findLongestPath(root.children.get(i), root.val, 1);
}
return longest;
}
public void findLongestPath(TreeNode root, int pre, int len) {
if(root == null) {
longest = Math.max(len, longest);
return;
}
if(root.children == null || root.children.size() == 0) {
longest = Math.max(len+1, longest);
return;
}
if(root.val > pre) {
for(int i=0; i<root.children.size(); i++) {
findLongestPath(root.children.get(i), root.val, len+1);
}
} else {
for(int i=0; i<root.children.size(); i++) {
findLongestPath(root.children.get(i), root.val, 1);
}
}
}
}