C# DFS


  • 0
    Y
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int SumNumbers(TreeNode root) {
            int res=0;
            if(root==null)
                return res;
            SumNumbersHelper(root, 0,ref res);
            return res;
        }
        
        private void SumNumbersHelper(TreeNode root, int cur,ref int res)
        {
            cur = cur*10 + root.val;
            if(root.left==null && root.right==null)//leaf
            {
                res += cur;
                return;
            }
            if(root.left!=null)
                SumNumbersHelper(root.left,cur,ref res);
            if(root.right!=null)
                SumNumbersHelper(root.right,cur,ref res);
        }
    }

Log in to reply
 

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