首页 > 其他 > 详细

Leetcode Binary Tree Paths

时间:2015-09-17 06:22:56      阅读:215      评论:0      收藏:0      [点我收藏+]

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

解题思路:

依然recursion! 用DFS。 关键点:让路径string 伴随着遍历树的点,点到哪里,路径值跟到哪里。


Java code:

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

Reference:

1. http://www.hihuyue.com/hihuyue/codepractise/leetcode/leetcode174-binary-tree-paths 

 

Leetcode Binary Tree Paths

原文:http://www.cnblogs.com/anne-vista/p/4815090.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!