/* * 129. Sum Root to Leaf Numbers * 2016-5-21 By Mingyang * dfs包含三种,这里是dfs的preorder方法,先解决根再是左右 */ public int sumNumbers(TreeNode root) { return dfs(root, 0); } public int dfs(TreeNode root, int levelBase) { if (root == null) return 0; if (root.left == null && root.right == null) { return levelBase + root.val; } int nextLevelBase = (levelBase + root.val) * 10; int leftSubTreeSum = dfs(root.left, nextLevelBase); int rightSubTreeSum = dfs(root.right, nextLevelBase); return leftSubTreeSum + rightSubTreeSum; } //自己的代码: public int sum=0; public int sumNumbers1(TreeNode root) { dfs1(root,0); return sum; } public void dfs1(TreeNode root,int base){ if(root==null) return; if(root.left==null&&root.right==null){ sum+=base*10+root.val; return; } base=base*10+root.val; if(root.left!=null) dfs1(root.left,base); if(root.right!=null) dfs1(root.right,base); }