My java solution of DFS


  • 1
    Z

    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public int rst = 0;
      public int sumNumbers(TreeNode root) {
      sum(root, 0);
      return rst;

      }

    public void sum(TreeNode root, int sum){
      if(root == null){
          return;
      }
      int temp = sum * 10 + root.val;
      if(root.left == null && root.right == null){
          rst = rst + temp;
          return;
      }
      sum(root.left, temp);
      sum(root.right, temp);
    }
    

    }


Log in to reply
 

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