中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
改了下,应该是对的
- public class LongestConsectiveIncreasingSequenceInBinaryTree {
- static class TreeNode {
- TreeNode left;
- TreeNode right;
- int val;
- public TreeNode(int val) {
- this.val = val;
- }
- }
- static class ResultType {
- int increaseNum;
- int decreaseNum;
- public ResultType(int i, int d) {
- this.increaseNum = i;
- this.decreaseNum = d;
- }
- }
- private static int res = 0;
- public static int getLongestConsectiveSequence(TreeNode root) {
- longestConsectiveSequence(root);
- return res;
- }
- public static ResultType longestConsectiveSequence(TreeNode root) {
- if (root == null) {
- return new ResultType(0, 0);
- }
- ResultType left = longestConsectiveSequence(root.left);
- ResultType right = longestConsectiveSequence(root.right);
- ResultType curRes = new ResultType(1, 1);
- if (root.left != null) {
- if (root.left.val > root.val) {
- curRes.increaseNum = left.increaseNum + 1;
- } else if (root.left.val < root.val) {
- curRes.decreaseNum = left.decreaseNum + 1;
- }
- }
- if (root.right != null) {
- if (root.right.val > root.val) {
- curRes.increaseNum = Math.max(right.increaseNum + 1,
- curRes.increaseNum);
- } else if (root.right.val < root.val) {
- curRes.decreaseNum = Math.max(right.decreaseNum + 1,
- curRes.decreaseNum);
- }
- }
- System.out.print("val " + root.val + " ");
- System.out.print(curRes.decreaseNum + " ");
- System.out.println(curRes.increaseNum + " ");
- int leftToRightInc = 1;
- int rightToLeftInc = 1;
- if (root.left != null) {
- if (root.left.val > root.val) {
- rightToLeftInc += left.increaseNum; // 2
- } else if (root.left.val < root.val) {
- leftToRightInc += left.decreaseNum; //0
- }
- }
- if (root.right != null) {
- if (root.right.val > root.val) {
- leftToRightInc += right.increaseNum;
- } else if (root.right.val < root.val) {
- rightToLeftInc += right.decreaseNum;
- }
- }
- res = Math.max(leftToRightInc, rightToLeftInc);
- return curRes;
- }
- public static void main(String[] args) {
- TreeNode root = new TreeNode(3);
- root.left = new TreeNode(2);
- root.right = new TreeNode(4);
- root.left.left = new TreeNode(2);
- root.left.right = new TreeNode(1);
- root.right.left = new TreeNode(6);
- System.out.println(getLongestConsectiveSequence(root));
- }
- }
复制代码 |
|