Java Solution , traverse the tree once


  • 0
    W

    class Solution {
    public int findTilt(TreeNode root) {
    if(root==null)
    return 0;
    int tilt = findTilt(root.left)+findTilt(root.right);
    root.val+=(valueOfNode(root.left)+valueOfNode(root.right));
    return tilt + Math.abs(valueOfNode(root.left)-valueOfNode(root.right));
    }
    private int valueOfNode(TreeNode node){
    if(node == null)
    return 0;
    return node.val;
    }
    }


Log in to reply
 

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