3个算法题目

2021-03-21  本文已影响0人  啊磊11

//二叉树展开为链表

public static void task37(TreeNode root){

if(root ==null){

return;

    }

task37(root.leftchild);

    task37(root.rightchild);

    TreeNode left = root.leftchild;

    TreeNode right = root.rightchild;

    root.leftchild =null;

    root.rightchild = left;

    TreeNode curr = root;

    while (curr !=null && curr.rightchild !=null){

curr = curr.rightchild;

    }

curr.rightchild = right;

}

//买卖股票的最佳时间

public static int task38(int[] nums){

int[][] dp =new int[nums.length][2];

    for(int i =0;i

if(i ==0){

dp[i][0] =0;

            dp[i][1] =0-nums[i];

continue;

        }

dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + nums[i]);

        dp[i][1] = Math.max(dp[i-1][1], 0-nums[i]);

    }

return dp[nums.length-1][0];

}

//二叉树中的最大路径和

public static int max = Integer.MIN_VALUE;

public static int task39(TreeNode root){

if (root ==null){

return 0;

    }

int left = Math.max(task39(root.leftchild),0);

    int right = Math.max(task39(root.rightchild),0);

    max = Math.max(max, left + right + root.value);

    return Math.max(left,right) + root.value;

}

上一篇 下一篇

猜你喜欢

热点阅读