337 House Robber III Java Solutions

Source: Internet
Author: User

The thief has found himself a new place for his thievery again. There is a entrance to this area, called the "root." Besides the root, each house have one and only one parent house. After a tour, the Smart thief realized the ' all houses in this ' place forms a binary tree. It would automatically contact the police if and directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3    /    2   3    \   \      3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

     3    /    4   5  /\   \  1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8  * }9  */Ten  Public classSolution { One      Public intRob (TreeNode root) { A         int[] res =Robdfs (root); -         returnMath.max (res[0],res[1]); -     } the      -      Public int[] Robdfs (TreeNode root) { -         if(Root = =NULL)return New int[2]; -         int[] left =Robdfs (root.left); +         int[] right =Robdfs (root.right); -         int[] ans =New int[2]; +Ans[0] = left[1] + root.val + right[1]; AANS[1] = Math.max (left[0], left[1]) + Math.max (right[0],right[1]); at         returnans; -     } -}

In Dfs, when Root is null, an empty array of length 2 is returned;
When the resulting array res is established, Res[0] is the case that includes the root node, and res[1] is not the root node. Instead of dividing it by the left and right sub-trees.

337 House Robber III Java Solutions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.