zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode笔记:257. Binary Tree Paths

2023-03-15 23:24:21 时间

问题:

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree:

image.png All root-to-leaf paths are: ["1->2->5", "1->3"]

大意:

给出一个二叉树,返回所有从根节点到叶子节点的路径。 比如给出下面这个二叉树:

image.png 所有从根节点到叶子节点的路径为: ["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<String>();
        if (root == null) return result;
        
        String path = String.valueOf(root.val);
        findPath(result, root, path);
        return result;
    }
    
    public void findPath(List<String> list, TreeNode root, String path) {
        if (root.left == null && root.right == null) {
            list.add(path);
            return;
        }
        if (root.left != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.left.val));
            findPath(list, root.left, pathBuffer.toString());
        } 
        if (root.right != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.right.val));
            findPath(list, root.right, pathBuffer.toString());
        }
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页