leetcode -- 257. Binary Tree Paths【遍历次序】

来源:互联网 发布:我的世界新手网络联机 编辑:程序博客网 时间:2024/06/06 07:34

题目

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

题意

给定一个二叉树,返回所有的root 到leaf的路径。(上面有相关示例)


分析及解答

(本质上都是二叉树的遍历,先序(从顶向下拼接)后序(从底向上拼接) 都可

方法1(后续遍历):

public List<String> binaryTreePaths(TreeNode root) {// 通过后续遍历的方式记录。List<String> paths = new ArrayList<>();if(root == null) return paths;if(root.left == null && root.right == null){paths.add(String.valueOf(root.val));return paths;}List<String> left = binaryTreePaths(root.left);List<String> right = binaryTreePaths(root.right);record(left, paths, root);record(right,paths,root);return paths;}public void record(List<String> src,List<String> tgt,TreeNode current){for(String data:src){tgt.add(current.val +"->"+data);}}

改进(整洁代码):

  • 【int 变字符串】 int + "" (空字符串)
  • 减少不必要的中间变量

public List<String> binaryTreePaths(TreeNode root) {                List<String> paths = new LinkedList<>();        if(root == null) return paths;                if(root.left == null && root.right == null){            paths.add(root.val+"");            return paths;        }         for (String path : binaryTreePaths(root.left)) {             paths.add(root.val + "->" + path);         }         for (String path : binaryTreePaths(root.right)) {             paths.add(root.val + "->" + path);         }         return paths;            }

方法2(先序遍历):

参考:(Accepted Java simple solution in 8 lines

public List<String> binaryTreePaths(TreeNode root) {    List<String> answer = new ArrayList<String>();    if (root != null) searchBT(root, "", answer);    return answer;}private void searchBT(TreeNode root, String path, List<String> answer) {    if (root.left == null && root.right == null) answer.add(path + root.val);    if (root.left != null) searchBT(root.left, path + root.val + "->", answer);    if (root.right != null) searchBT(root.right, path + root.val + "->", answer);}





0 0
原创粉丝点击