*LeetCode- Sum Root to Leaf Numbers

来源:互联网 发布:wpf高级编程 pdf 编辑:程序博客网 时间:2024/06/16 15:36

这个题一开始一直想从叶子开始加,后来发现从root向下走比较方便。递归函数传一个记录到达当前节点的和。

recursive:

public class Solution {    public int sumNumbers(TreeNode root) {        return sum(root,0);    }    public int sum (TreeNode root, int sumNow){        if ( root == null )            return 0;        if ( root.left == null && root.right == null )            return sumNow = sumNow*10 + root.val;        return sum(root.left, sumNow*10 + root.val) + sum (root.right, sumNow * 10 + root.val);            }}
注意判断的是root是否为空,是否为叶子


iterative:stack实现的dfs 这个应该就是bottom up的

public static int sumNumbers(TreeNode root) {    int sum = 0, num = 0;    TreeNode lastVisited = null;    Stack<TreeNode> s = new Stack<>();    while (root != null || !s.isEmpty()) {        if (root != null) {            s.push(root);            num = num * 10 + root.val;            root = root.left;        } else {            TreeNode peek = s.peek();            if (peek.right != lastVisited && peek.right != null) {                root = peek.right;            } else {                if (peek.left == null && peek.right == null) {                    sum += num;                }                s.pop();                num /= 10;                lastVisited = peek;            }        }    }    return sum;}


0 0