LeetCode -- Binary Tree Paths

Question:

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"]

 Analysis:

问题描述:给出一棵二叉树,给出所有根节点到叶子节点的路径。

思路一:递归

Answer:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<String> res = new ArrayList<String>();
    public List<String> binaryTreePaths(TreeNode root) {
        if(root != null)
            findPath(root, Integer.toString(root.val));
        return res;
    }
    
    public void findPath(TreeNode root, String string) {
        // TODO Auto-generated method stub
        if(root.left == null && root.right == null)
            res.add(string);
        if(root.left != null)
            findPath(root.left, string + "->" + Integer.toString(root.left.val));
        if(root.right != null)
            findPath(root.right, string + "->" + Integer.toString(root.right.val));
    }
}

思路二:深度优先遍历,用栈保存遍历过的节点。

原文地址:https://www.cnblogs.com/little-YTMM/p/4844331.html