import
java.util.ArrayDeque;
import
java.util.HashSet;
import
java.util.Queue;
import
java.util.Set;
class
TreeNode {
int
val;
TreeNode left;
TreeNode right;
TreeNode(
int
x) {
val = x;
left =
null
;
right =
null
;
}
}
class
Solution {
public
int
rob(TreeNode root) {
Set<TreeNode> dp =
new
HashSet<>();
return
robb(root, dp);
}
private
int
robb(TreeNode root, Set<TreeNode> dp) {
if
(root ==
null
) {
return
0
;
}
if
(dp.contains(root)) {
return
root.val;
}
int
notPick =
0
;
int
pick =
0
;
int
left =
0
;
int
right =
0
;
if
(root.left !=
null
) {
left = robb(root.left.left, dp) + robb(root.left.right, dp);
}
if
(root.right !=
null
) {
right = robb(root.right.left, dp) + robb(root.right.right, dp);
}
pick = root.val + left + right;
notPick = robb(root.left, dp) + robb(root.right, dp);
root.val = Math.max(pick, notPick);
dp.add(root);
return
root.val;
}
}
public
class
Main {
public
static
TreeNode buildTree(String s) {
if
(s.length() ==
0
|| s.charAt(
0
) ==
'N'
) {
return
null
;
}
String[] ip = s.split(
"\\s+"
);
TreeNode root =
new
TreeNode(Integer.parseInt(ip[
0
]));
int
size =
0
;
Queue<TreeNode> q =
new
ArrayDeque<>();
q.offer(root);
size++;
int
i =
1
;
while
(size >
0
&& i < ip.length) {
TreeNode currNode = q.poll();
size--;
String currVal = ip[i];
if
(!currVal.equals(
"N"
)) {
currNode.left =
new
TreeNode(Integer.parseInt(currVal));
q.offer(currNode.left);
size++;
}
i = i +
1
;
if
(i >= ip.length) {
break
;
}
currVal = ip[i];
if
(!currVal.equals(
"N"
)) {
currNode.right =
new
TreeNode(Integer.parseInt(currVal));
q.offer(currNode.right);
size++;
}
i = i +
1
;
}
return
root;
}
public
static
void
main(String[] args) {
String s =
"3 4 5 1 3 N 1"
;
TreeNode root = buildTree(s);
Solution ob =
new
Solution();
System.out.println(ob.rob(root));
}
}