C# solution: DFS and Sum


  • 0
    B
    public class Solution 
    {
        public bool CheckEqualTree(TreeNode root) 
        {
            if (root == null) return false;
            if (root.left == null && root.right == null) return false;
    
            return DFS(root, 0);
        }
    
        private bool DFS(TreeNode root, int sum)
        {
            if (root == null) return false;
    
            var leftSum = SumDFS(root.left);
            var rightSum = SumDFS(root.right);
    
            if (leftSum + root.val + sum == rightSum || leftSum == rightSum + root.val + sum)
            {
                return true;
            }
    
            return DFS(root.right, root.val + leftSum + sum) || DFS(root.left, root.val + rightSum + sum);
        }
    
        Dictionary<TreeNode, int> treeNodeAndSum = new Dictionary<TreeNode, int>();
    
        private int SumDFS(TreeNode root)
        {
            if (root == null) return 0;
    
            if (treeNodeAndSum.ContainsKey(root)) return treeNodeAndSum[root];
    
            var result = SumDFS(root.left) + SumDFS(root.right) + root.val;
            treeNodeAndSum[root] = result;
    
            return result;
        }
    }
    
    

Log in to reply
 

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