Solution by Tree's PreOrder() Java


  • 0
    K

    /**

    • Definition for binary tree
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      int count = 0;
      public int sumNumbers(TreeNode root) {
      preorder(root);
      return count;
    }
    public void preorder(TreeNode node){
        if(node != null){
            //visit
            if( node.left == null && node.right == null){
                count += node.val;
            }else{
                
            
            if(node.left != null){
                node.left.val = node.val*10 +node.left.val;
            }
            
            if(node.right != null){
                node.right.val = node.val*10 + node.right.val;
            }
            
            }
            
            preorder(node.left);
            preorder(node.right);
        }
    }
    

    }


Log in to reply
 

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