Easiest postorder without global variable


  • 0
    H
    public class Solution {
        public int findTilt(TreeNode root) {
            int[] sum = new int[1];
            dfs(root, sum);
            return sum[0];
        }
        
        public int dfs(TreeNode root, int[] sum) {
            if (root == null) {
                return 0;
            }
            int left = dfs(root.left, sum);
            int right = dfs(root.right, sum);
            sum[0] += Math.abs(right - left);
            return left + right + root.val;
        }
    }
    

Log in to reply
 

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