首页 > 其他 > 详细

Binary Tree Paths

时间:2015-08-27 16:44:35      阅读:269      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode.com/submissions/detail/37771540/

题目

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

题意:找出给定二叉树中的所有路径

分析:遍历每个节点,记录其路径(如果当前节点有子节点,则调用递归继续遍历其子节点,并记录新路径,删除之前路径)

代码

/**
 * 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<>();
        if(root==null) 
            return result;
        searchPaths(root, "", result);
        return result;
    }
    
    public void searchPaths(TreeNode root, String curPath, List<String> result) {
        String updatePath;
        
        if(root.left == null && root.right == null) {
            updatePath = curPath + root.val;
            result.add(updatePath);
            result.remove(curPath);
        }
        
        if(root.left != null || root.right != null) {
            updatePath = curPath + root.val + "->";
            result.add(updatePath);
            result.remove(curPath);
            
            if(root.left != null)
                searchPaths(root.left, updatePath, result);
            
            if(root.right != null)
                searchPaths(root.right, updatePath, result);
        }
    }
}






































版权声明:本文为博主原创文章,未经博主允许不得转载。

Binary Tree Paths

原文:http://blog.csdn.net/yangyao_iphone/article/details/48028729

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