当前位置: 代码迷 >> 综合 >> leetcode题解(257) Binary Tree Paths(打印所有二叉树根节点到叶节点的路径)
  详细解决方案

leetcode题解(257) Binary Tree Paths(打印所有二叉树根节点到叶节点的路径)

热度:78   发布时间:2023-09-19 08:21:04.0

题目描述:

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:1/   \
2     3\5Output: ["1->2->5", "1->3"]Explanation: All root-to-leaf paths are: 1->2->5, 1->3

解题思路:这题说是简单题,其实如果不经常做回溯的问题也不容易一下做出来,设置一个列表或者StringBuffer用来存储根节点到当下节点的路径,然后依次深度优先遍历,判断遍历到节点是否是叶子节点,如果是,把列表或者StringBuffer存储到List中

代码如下:

class Solution {public int len;public List<String> binaryTreePaths(TreeNode root) {List<String> list = new ArrayList<>();if(root == null){return list;}StringBuilder sb = new StringBuilder();len = (root.val + "").length();backtracking(list, root, sb);return list;}public void backtracking(List<String> list, TreeNode root, StringBuilder sb){if(root != null){if(sb.length() == 0)sb.append(root.val + "");elsesb.append("->" + root.val);}else{return;}if(isLeaf(root)){list.add(sb.toString());}else{backtracking(list, root.left, sb);backtracking(list, root.right, sb);} if(sb.length() != len)sb.delete(sb.length() - ("->"+root.val).length(), sb.length());}public boolean isLeaf(TreeNode node){return (node.left == null && node.right == null);}}

 

  相关解决方案