|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * function TreeNode(val) { |
| 4 | + * this.val = val; |
| 5 | + * this.left = this.right = null; |
| 6 | + * } |
| 7 | + */ |
| 8 | +/** |
| 9 | + * Key: similar to every house in previous hourse rob problems, each node store two values, |
| 10 | + * first value is to store the max value if the node will be robbed. The second value is the vaule |
| 11 | + * if the node will not be robbed. |
| 12 | + * In the first case, the value is straightforward to calculate, that is, current node's val |
| 13 | + * plus the second value from it's child nodes' second value (not robbed). |
| 14 | + * In the second case, because the node is not going to be robbed, its children can be robbed |
| 15 | + * or not robbed. So the value is the max value of the left child's two values plus the right child's |
| 16 | + * max value from the two values. |
| 17 | + * |
| 18 | + *@param {TreeNode} root |
| 19 | + *@return {number} |
| 20 | + */ |
| 21 | +varrob=function(root){ |
| 22 | +varresult=robDFS(root); |
| 23 | +returnMath.max(result[0],result[1]); |
| 24 | +}; |
| 25 | + |
| 26 | +varrobDFS=function(root){ |
| 27 | +if(!root)return[0,0]; |
| 28 | +varresult=[]; |
| 29 | +varleftResults=robDFS(root.left); |
| 30 | +varrightResults=robDFS(root.right); |
| 31 | +result[0]=root.val+leftResults[1]+rightResults[1]; |
| 32 | +result[1]=Math.max(leftResults[0],leftResults[1])+Math.max(rightResults[0],rightResults[1]); |
| 33 | +returnresult; |
| 34 | +}; |
| 35 | + |
| 36 | + |
| 37 | +// not right, why? |
| 38 | +varrob=function(root){ |
| 39 | +varcachedResult={}; |
| 40 | +returnrobHelper(root,cachedResult); |
| 41 | +}; |
| 42 | + |
| 43 | +varrobHelper=function(root,cachedResult){ |
| 44 | +if(!root)return0; |
| 45 | +if(cachedResult.hasOwnProperty(root)){ |
| 46 | +returncachedResult[root]; |
| 47 | +} |
| 48 | +varval=0; |
| 49 | + |
| 50 | +if(root.left!==null){ |
| 51 | +val+=robHelper(root.left.left,cachedResult)+robHelper(root.left.right,cachedResult); |
| 52 | +console.log(root,val); |
| 53 | +} |
| 54 | + |
| 55 | +if(root.right!==null){ |
| 56 | +val+=robHelper(root.right.left,cachedResult)+robHelper(root.right.right,cachedResult); |
| 57 | +console.log(root,val); |
| 58 | + |
| 59 | +} |
| 60 | + |
| 61 | +val=Math.max(val+root.val,robHelper(root.left,cachedResult)+robHelper(root.right,cachedResult)); |
| 62 | +cachedResult[root]=val; |
| 63 | + |
| 64 | +returnval; |
| 65 | +}; |