给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

示例:

输入: 38
输出: 2 
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。

进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

上期的问题是:168,二叉树的所有路径

 1public List<String> binaryTreePaths(TreeNode root) {
 2    List<String> answer = new ArrayList<>();
 3    if (root != null) searchBT(root, "", answer);
 4    return answer;
 5}
 6
 7private void searchBT(TreeNode root, String path, List<String> answer) {
 8    if (root.left == null && root.right == null) answer.add(path + root.val);
 9    if (root.left != null) searchBT(root.left, path + root.val + "->", answer);
10    if (root.right != null) searchBT(root.right, path + root.val + "->", answer);
11}

解析:

通过递归的方式,代码很好理解。下面再看另一种写法dfs深度优先搜索

 1public List<String> binaryTreePaths(TreeNode root) {
 2    List<String> res = new ArrayList<>();
 3    if (root == null)
 4        return res;
 5    Stack<Object> stack = new Stack<>();
 6    stack.push(root);
 7    stack.push("");
 8    while (!stack.isEmpty()) {
 9        String ls = (String) stack.pop();
10        TreeNode node = (TreeNode) stack.pop();
11        if (node.left == null && node.right == null) {
12            res.add(ls + node.val);
13        }
14        if (node.right != null) {
15            stack.push(node.right);
16            stack.push(ls + node.val + "->");
17        }
18        if (node.left != null) {
19            stack.push(node.left);
20            stack.push(ls + node.val + "->");
21        }
22    }
23    return res;
24}

这个也容易理解,每次push的时候,先push节点,然后再push字符串。再来看一种方法,bfs宽度优先搜索

 1public List<String> binaryTreePaths(TreeNode root) {
 2    List<String> res = new ArrayList<>();
 3    if (root == null)
 4        return res;
 5    Queue<Object> queue = new LinkedList<>();
 6    queue.offer(root);
 7    queue.offer("");
 8    while (!queue.isEmpty()) {
 9        TreeNode node = (TreeNode) queue.poll();
10        String ls = (String) queue.poll();
11        if (node.left == null && node.right == null) {
12            res.add(ls + node.val);
13        }
14        if (node.left != null) {
15            queue.offer(node.left);
16            queue.offer(ls + node.val + "->");
17        }
18        if (node.right != null) {
19            queue.offer(node.right);
20            queue.offer(ls + node.val + "->");
21        }
22    }
23    return res;
24}

这个使用的是队列,和dfs的区别是,dfs先push右子节点,然后再push左子节点,而bfs是先把左子节点加入到队列中然后再把右子节点加入到队列中。因为栈是先进后出,队列是先进先出。当然我们还可以使用递归的方式,看下代码

 1public List<String> binaryTreePaths(TreeNode root) {
 2    List<String> paths = new LinkedList<>();
 3    if (root == null) return paths;
 4    if (root.left == null && root.right == null) {
 5        paths.add(root.val + "");
 6        return paths;
 7    }
 8    for (String path : binaryTreePaths(root.left)) {
 9        paths.add(root.val + "->" + path);
10    }
11    for (String path : binaryTreePaths(root.right)) {
12        paths.add(root.val + "->" + path);
13    }
14    return paths;
15}