LeetCode题解-129-Sum Root to Leaf Numbers

原题

LeetCode题解-129-Sum Root to Leaf Numbers_第1张图片

原题链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/


解法概览

解法1:迭代法,后序遍历

解法2:递归法


解法1

解法分析

进行后序遍历,每次到达叶子节点的时候,计算栈中所有元素组成的数字的值,并加到sum中。

后序遍历的方法与图解请见:http://blog.csdn.net/wangt443/article/details/51863846


代码

public class Solution129_DFS_iterator {
    public int sumNumbers(TreeNode root) {
        int sum = 0;
        TreeNode lastVisit = null;
        Deque stack = new LinkedList();
        if (root != null)
            stack.push(root);

        while (!stack.isEmpty()){
            while (stack.peek() != null){
                TreeNode currentNode = stack.peek();
                stack.push(currentNode.left);
            }
            stack.pop();

            if (!stack.isEmpty()){
                TreeNode currentNode = stack.peek();
                if (currentNode.right == null || currentNode.right == lastVisit){
                    if (currentNode.left == null && currentNode.right == null){
                        int number = countNumber(stack);
                        sum += number;
                    }

                    lastVisit = stack.pop();
                    stack.push(null);
                }
                else
                    stack.push(currentNode.right);
            }
        }
        return sum;
    }

    private int countNumber(Deque stack){
        int size = stack.size(), number = 0;
        for (TreeNode treeNode : stack) {
            number += treeNode.val * Math.pow(10, stack.size() - size);
            size--;
        }
        return number;
    }
}


解法2

解法分析

递归,i为父节点所产生的值,例如对于图解中的3来说,i为节点1与节点2产生的值,为i = 12.当当前为叶子节点时,i * 10 + 当前节点的值即可;当当前节点仍有子树的时候,递归计算并返回 左子树的递归值+右子树的递归值, 其中传递给子树的i = i *10 + root.val.

图解

LeetCode题解-129-Sum Root to Leaf Numbers_第2张图片

代码

public class Solution129_recursive {
    public int sumNumbers(TreeNode root) {
        return sumNumbersHelper(root, 0);
    }

    private int sumNumbersHelper(TreeNode root, int i) {
        if (root == null)
            return 0;
        if (root.right == null && root.left == null)
            return i * 10 + root.val;
        return sumNumbersHelper(root.left, i*10 + root.val)
                + sumNumbersHelper(root.right, i*10 + root.val);
    }
}











你可能感兴趣的:(LeetCode,LeetCode,Tree,后序遍历,递归,BFS)