257. Binary Tree Paths

该题是找出所有由根到树叶的所有路径,主要解决思路是二叉树的前序遍历。要注意的是在遍历节点时要判断是否为树叶节点,是的话要将 节点数值 + "->" 的形式加在临时字符串后面, 否则仅仅将 节点数值 加在后面就好了。

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        
        helper(root, res, "");
        
        return res;
    }
    
    private void helper(TreeNode root, List<String> res, String tmp){
        if(root == null){
            return;
        }
        
        if(root.left == null && root.right == null){
            tmp += root.val;
            res.add(tmp);
            return;
        }else{
            tmp += root.val + "->";
        }
            
        helper(root.left, res, tmp);
        helper(root.right, res, tmp);
        
    }
}

END

原文地址:https://www.cnblogs.com/sssysukww/p/8853706.html