zoukankan      html  css  js  c++  java
  • leetcode337

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int Rob(TreeNode root)
            {
                int[] num = dfs(root);
                return Math.Max(num[0], num[1]);
            }
    
            private int[] dfs(TreeNode x)
            {
                if (x == null) return new int[2];
                int[] left = dfs(x.left);
                int[] right = dfs(x.right);
                int[] res = new int[2];
                res[0] = left[1] + right[1] + x.val;
                res[1] = Math.Max(left[0], left[1]) + Math.Max(right[0], right[1]);
                return res;
            }
    }

    https://leetcode.com/problems/house-robber-iii/#/description

    补充一个python的实现:

     1 class Solution:
     2     def dfs(self,root):
     3         if root==None:
     4             return [0,0]#空节点
     5         counter = [0,0]
     6         left = self.dfs(root.left)
     7         right = self.dfs(root.right)
     8 
     9         #取当前节点,则其左右子节点都不能取
    10         counter[0] =  root.val + left[1] + right[1]
    11         
    12         #不取当前节点,则左右子节点是否选取要看子节点选择是否更大
    13         counter[1] = max(left[0],left[1]) + max(right[0],right[1])
    14         return counter
    15 
    16     def rob(self, root: 'TreeNode') -> 'int':
    17         result = self.dfs(root)
    18         #第一位表示取当前节点的累计值,第二位表示不取当前节点的累计值
    19         return max(result[0],result[1])
  • 相关阅读:
    java面试题
    linux下的文件目录结构
    Linux的基础命令
    Linux系统的介绍
    逻辑思维题
    37-字符的全排列
    36-螺旋矩阵
    35-面试:如何找出字符串的字典序全排列的第N种
    34-数细线
    33-求极差
  • 原文地址:https://www.cnblogs.com/asenyang/p/6970247.html
Copyright © 2011-2022 走看看