【2错】Binary Tree Tilt

https://leetcode.com/problems/binary-tree-tilt/

日期 是否一次通过 comment
2018-12-26 14:01 看答案,并手推复现 对postOrder理解不够深 & 递归其实返回的是上一层
2019-01-13 16:41 二次通过 语法问题,漏掉“1”(int[] tempSum = new int[1];)
【2错】Binary Tree Tilt_第1张图片
image.png

(来源: https://leetcode.com/problems/binary-tree-tilt/)

实际上是个postOrder遍历二叉树,关键在于return时,要加上root.val,这样做是因为递归返回的其实是上一层;只有加上val后,得到的才是|sum(leftTreeNode.vals) - sum(rightTreeNode.vals) |。

递归

class Solution {
    public int findTilt(TreeNode root) {
        if(root == null) {
            return 0;
        }
        
        int[] tempSum = new int[1];
        postOrder(root, tempSum);
        
        return tempSum[0];
    }
    
    private int postOrder(TreeNode root, int[] tempSum) {
        if(root == null) {
            return 0;
        }
        
        int leftVal = postOrder(root.left, tempSum);
        int rightVal = postOrder(root.right, tempSum);
        tempSum[0] += Math.abs(rightVal - leftVal);
        
        return leftVal + rightVal + root.val;
    }
}

你可能感兴趣的:(【2错】Binary Tree Tilt)