c# recursive solution


  • 0
    N
    public class Solution {
        int total = 0;
        Dictionary<TreeNode, int> tilts = new Dictionary<TreeNode, int>();
    
        public int FindTilt(TreeNode root) {
            if (root == null) return 0;
            
            dfs(root);
            
            return total;
        }
        
        public int dfs(TreeNode node){
            if(node == null) return 0;
            var sum = 0;
            
            var left =  dfs(node.left);
            var right = dfs(node.right);
            if(!tilts.ContainsKey(node)){
                total += Math.Abs(left-right);
            }
            else {
                tilts[node] = Math.Abs(left-right);
            }
            return left+ right + node.val;
        }
    }
    

Log in to reply
 

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