首页 > 代码库 > 257. Binary Tree Paths

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

思路: dfs,搜索到leaf停下,存到res。我用的stringbuilder,在回溯的时候怎么变回到之前的状态没想出来。参考了discussion里的一种办法,setlength。马丹,差一点啊,看了答案心情舒畅多了。
/** * 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> res=new ArrayList<String>();        StringBuilder save=new StringBuilder();        dps(root,res,save);        return res;    }    public void dps(TreeNode root, List<String> res, StringBuilder sb)    {        if(root==null)        {            return;        }        int length=sb.length();        if(root.left==null&&root.right==null)        {            sb.append(root.val);            res.add(sb.toString());            sb.setLength(length);            return;        }        sb.append(root.val);        sb.append("->");        dps(root.left,res,sb);        dps(root.right,res,sb);        sb.setLength(length);    }            }

 

多理解理解回溯的点,也就是return时候的条件。

257. Binary Tree Paths