zoukankan      html  css  js  c++  java
  • 563 Binary Tree Tilt

    Given a binary tree, return the tilt of the whole tree.
    
    The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values
    and the sum of all right subtree node values. Null node has tilt 0. The tilt of the whole tree is defined as the sum of all nodes' tilt. Example: Input: 1 / 2 3 Output: 1 Explanation: Tilt of node 2 : 0 Tilt of node 3 : 0 Tilt of node 1 : |2-3| = 1 Tilt of binary tree : 0 + 0 + 1 = 1 Note: The sum of node values in any subtree won't exceed the range of 32-bit integer. All the tilt values won't exceed the range of 32-bit integer.

    这道题让我们求二叉树的坡度,某个结点的坡度的定义为该结点的左子树之和与右子树之和的差的绝对值,这道题让我们求所有结点的坡度之和. 这道题最好的解法应该是用后序遍历来做,因为后序遍历的顺序是左-右-根,那么就会从叶结点开始处理,这样我们就能很方便的计算结点的累加和,同时也可以很容易的根据子树和来计算tilt,

    public class Solution {
        int ans = 0;
        public int findTilt(TreeNode root) {	
            
            if (root == null) {
                return ans;
            }
            helper(root);
            return ans;
        }
        private int helper(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftSum = helper(root.left);
            int rightSum = helper(root.right);
            
            ans += Math.abs(leftSum - rightSum);
            return leftSum + rightSum + root.val;
        }
    }
    

    分治法原来就是后序遍历, 遍历到节点在处理, 然后返回到上层节点, 

    算法: 分治, 后序遍历( 在设计求 结点的左子树之和与右子树之和的基础上, 设计全局变量分治法求的差的绝对值)

    容器: 全局变量, (要明白返回值是各个节点的子节点和, 而tilt 是总的, 都在变化, 只有子节点的可以当作返回值, 然后和是各个节点的tilt 和) 所以返回值的设定是子树的和!!

  • 相关阅读:
    POJ 3263 Tallest Cow(线段树)
    面试题54——表示数值的字符串
    ORA-01555错误总结(二)
    《AndroidStudio每日一贴》11. 重构之提炼为常量
    机器学习系统构建
    jsp不通过form和Ajax提交
    南邮算法分析与设计实验2 动态规划法
    cocos2d-x 3.2 之 2048 —— 第五篇
    Cocos2d-x学习资源集锦+有奖抽楼活动
    VMware虚拟机无法识别U盘解决方式
  • 原文地址:https://www.cnblogs.com/apanda009/p/7265958.html
Copyright © 2011-2022 走看看