题目:对于一个二叉树,不能同时取某个分支上两端的两个节点,求能取得的最大的值。(这是题目大意)
思路:对于一个二叉树,如果根据条件判断该二叉树根节点可以取,则传入参数true,如果某个二叉树的根节点不可以取,则传入false,当参数为true时,到底真正取与不去分两种情况,类似于0-1背包问题,然后返回那个结果比较大的情况。当参数为false,则根节点一定是不能取了,则返回(root.left,true)+(root.right,true)。
我用的是纯递归写的,可能效率比较低,在leetcode上提交,时间超过1000ms,不过就是思维相对简单。
我的leetcode的所有代码已经放入github:https://github.com/gaohongbin/leetcode
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int rob(TreeNode root) {
if(root == null)
return 0;
return helper(root,true);
}
public int helper(TreeNode root,boolean flag){ //flag为true表示可以取root的值,flag为false表示不能取root的值
if(root == null)
return 0;
if(flag == false){ //不能取root的值
int left = helper(root.left,true);
int right = helper(root.right,true);
return left+right;
}
else{ //root可以取
int hasRoot = root.val + helper(root.left,false)+helper(root.right,false); //取root的值
int noRoot = helper(root.left,true)+helper(root.right,true);//不取root的值
if(hasRoot>noRoot)
return hasRoot;
return noRoot;
}
}
}