LeetCode-Binary Tree Paths

Posted LiBlog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-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"]

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 Solution:
/**
 * 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> resList = new LinkedList<String>();
        StringBuilder builder = new StringBuilder();
        binaryTreePaths(root,builder,resList);
        return resList;
    }
    
    public void binaryTreePaths(TreeNode cur, StringBuilder builder, List<String> resList){
        if (cur==null){
            return;
        }
        
        builder.append(cur.val);
        if (cur.left==null && cur.right==null){
            resList.add(builder.toString());
            return;
        }
        
        builder.append("->");
        int len = builder.length();
        binaryTreePaths(cur.left,builder,resList);
        builder.setLength(len);
        binaryTreePaths(cur.right,builder,resList);
    }
}

 

以上是关于LeetCode-Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Binary Tree Right Side View

LeetCode-Binary Tree Preorder Traversal[二叉树]

74-递归函数2:tree功能显示

LeetcodeBinary Tree Maximum Path Sum

Binary Tree Maximum Path Sum

Binary Tree Path Sum Lintcode