337. House Robber III
每个结点有两个结果:
1. result[ 0 ], 不偷, 需要加上子节点的最大值,left[ 0 ] , left[ 1 ] 的最大值 + right[ 0 ], right[ 1 ]
2. result[ 1 ], 偷, 加上子节点不偷的值, left[ 0 ] + right[ 0 ] + 本节点 . val
class Solution { public int rob(TreeNode root) { int[] result = robHelper(root); return Math.max(result[0], result[1]); } private int[] robHelper(TreeNode root){ //[0] is max value if not rob current one //[1] is max value if rob current one if(root == null) return new int[2]; int result[] = new int[2]; int[] left = robHelper(root.left); int[] right = robHelper(root.right); result[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); result[1] = left[0] + right[0] + root.val; return result; } }
103. Binary Tree Zigzag Level Order Traversal
层序遍历的基本BFS算法,加一个level变量,当level为奇数时用Collections.reverse反转。
如果是level order, 用BFS,Queue保存下一个level要处理的节点以保证每一层从左到右遍历的顺序
class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if(root == null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int level = 0; while(!queue.isEmpty()){ int size = queue.size(); List<Integer> list = new ArrayList<>(); for(int i = 0; i < size; i++){ TreeNode node = queue.remove(); list.add(node.val); if(node.left != null){ queue.add(node.left); } if(node.right != null){ queue.add(node.right); } } if(level % 2 == 1){ Collections.reverse(list); } result.add(list); level++; } return result; } }