解题思路
res[0]表示当前节点下一步向左走带来的最大收益,res[1]表示当前节点下一步向右走带来的最大收益
res[0]=1+left[1] 当前节点下一步向左走带来的最大收益等于左子节点向右走的最大收益+1
res[1]=1+right[0] 当前节点下一步向右走带来的最大收益等于右子节点向左走的最大收益+1
package LeetCode.OneThousandMore;
import LeetCode.TreeNode;
public class OneThousandThreeHundredAndSeventhTwo {
private int max;
public int longestZigZag(TreeNode root) {
// 一道很明显的dp题
helper(root);
return max;
}
private int[] helper(TreeNode root) {
int[] res = new int[2];
// 用res[0]来表示当前节点走左子树最大的值,res[1]表示右子树最大的值
if (root == null){
res[0] = res[1] = -1;
return res;
}
int[] left = helper(root.left);
int[] right = helper(root.right);
// 因为是交叉的,所以当前是左下一个就要访问右子树,右子树则相反
res[0] = left[1] + 1;
res[1] = right[0] + 1;
max = Math.max(max,Math.max(res[0], res[1]));
return res;
}
}