【LeetCode】Binary Tree Paths 解题报告

来源:互联网 发布:收入词典的网络词语 编辑:程序博客网 时间:2024/05/20 16:33

【LeetCode】Binary Tree Paths 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/binary-tree-paths/#/description

题目描述:

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

For example, given the following binary tree:

 Example:

   1 /   \2     3 \  5All root-to-leaf paths are:["1->2->5", "1->3"]

Ways

把二叉树的从根节点到叶子节点的每条路径都打印出来,实用的方法就是很简单的递归调用。如果是叶子就把这个路径保存到list中,如果不是叶子就把这个节点的值放入到path中,然后再继续调用,直到达到叶子节点为止。

我用StringBuilder的结果会糅杂在一起,就不能用,也没想明白为什么= =

/** * 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> ans = new ArrayList<String>();        if(root != null){            searchNode(root, "", ans);        }        return ans;    }    public void searchNode(TreeNode root, String path, List<String> ans){        if(root.left == null && root.right == null){            ans.add(path + root.val);        }        if(root.left != null){            searchNode(root.left, path + root.val + "->", ans);        }        if(root.right != null){            searchNode(root.right, path + root.val + "->", ans);        }    }}

Date

2017 年 5 月 6 日

0 0
原创粉丝点击