LeetCode笔记:257. Binary Tree Paths

问题:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
/ \
2 3
\
5

All root-to-leaf paths are:

[“1->2->5”, “1->3”]

大意:

给出一个二叉树,返回所有从根节点到叶子节点的路径。

比如给出下面这个二叉树:

1
/ \
2 3
\
5

所有从根节点到叶子节点的路径为:

[“1->2->5”, “1->3”]

思路:

这道题适合用递归,依次判断有没有左右叶子节点,分别去做递归,在递归中把遇到的节点值拼接到路径字符串的最后,注意要拼接“->”这个内容,直到没有左右子节点后,表示已经到了叶子节点了,就可以终止了,把这条路径的字符串添加到结果中去。

代码:

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        if (root == null) return result;

        String path = String.valueOf(root.val);
        findPath(result, root, path);
        return result;
    }

    public void findPath(List<String> list, TreeNode root, String path) {
        if (root.left == null && root.right == null) {
            list.add(path);
            return;
        }
        if (root.left != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.left.val));
            findPath(list, root.left, pathBuffer.toString());
        } 
        if (root.right != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.right.val));
            findPath(list, root.right, pathBuffer.toString());
        }
    }
}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

你可能感兴趣的:(LeetCode)