129. Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / 
  2   3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

递归的题分为考察:

分治? 先序? 中序? 先序输入值? 全局辅助值? 全局结果值? 

分治法(后序遍历), 先序输入值, 后序结果值 + 叶结点(叶结点也要操作 sum * 10 类似 513. Find Bottom Left Tree Value中的deep )

这是一道树的题目,一般使用递归来做,主要就是考虑递归条件和结束条件。这道题思路还是比较明确的,目标是把从根到叶子节点的所有路径得到的整数都累加起来,递归条件即是把当前的sum乘以10并且加上当前节点传入下一函数,进行递归,最终把左右子树的总和相加。结束条件的话就是如果一个节点是叶子,那么我们应该累加到结果总和中,如果节点到了空节点,则不是叶子节点,不需要加入到结果中,直接返回0即可。算法的本质是一次先序遍历,所以时间是O(n),空间是栈大小,O(logn)。代码如下: 

public class Solution {
    public int sumNumbers(TreeNode root) {
        int ans = helper(root, 0);
        return ans;
    }
    private int helper(TreeNode root, int sum) {
        // 处理空节点
        if (root == null) return 0;
        //处理叶结点
        if (root.left == null && root.right == null) {
            return sum * 10 + root.val;
        }
        // 在遍历的时候的操作, 只是改变输入值, 每一层都有返回, 画图! 回溯!
       int left = helper(root.left, sum * 10 + root.val);
       int right =  helper(root.right, sum * 10 + root.val);
       return left + right;
        
    }
}

  

原文地址:https://www.cnblogs.com/apanda009/p/7296044.html