[LeetCode] 257. Binary Tree Paths

    xiaoxiao2024-01-26  133

    原题链接: https://leetcode.com/problems/binary-tree-paths/

    1. 题目介绍

    Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. 给出一个二叉树,返回所有从根节点到叶子节点的路径。

    Example:

    2. 解题思路

    使用深度优先搜索的方法,依次将根节点、左子树、右子树的值放入list中,当到达叶子节点的时候,使用StringBuffer 类记录 list 中的路径,然后将其转换为字符串放入结果集中。然后从list中删除这个叶子节点,继续寻找其他的路径。 实现代码

    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> s = new ArrayList<>(); List<Integer> t = new ArrayList<>(); helper(s,t,root); return s; } public void helper(List<String> s, List<Integer> t, TreeNode root){ if(root == null){ return; } if(root.left == null && root.right == null){ t.add(root.val); StringBuffer buf = new StringBuffer(); for(int i = 0; i<t.size() ; i++){ if(i == 0){ buf.append( t.get(i) ); }else{ buf.append("->" + t.get(i)); } } s.add(buf.toString()); t.remove(t.size()-1); return; } t.add(root.val); helper(s , t , root.left); helper(s , t , root.right); t.remove(t.size()-1); } }
    最新回复(0)