DFS easy to understand


  • 0
    Y
    public class Solution {
        public int rob(TreeNode root) {
            if (root == null) {
                return 0;
            }
            if (root.left == null && root.right == null) {
                return root.val;
            }
            
            int max = 0;
            
            if (root.left == null && root.right != null) {
                max = Math.max(root.val + rob(root.right.left) + rob(root.right.right), rob(root.right));
            }
            if (root.left != null && root.right == null) {
                max = Math.max(root.val + rob(root.left.left) + rob(root.left.right), rob(root.left));
            }
            if (root.left != null && root.right != null) {
                max = Math.max(root.val + rob(root.left.left) + rob(root.left.right) + rob(root.right.left) + rob(root.right.right), rob(root.left) + rob(root.right));
            }
            return max;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.