Skip to content

Latest commit

 

History

History
80 lines (63 loc) · 1.4 KB

20201123.md

File metadata and controls

80 lines (63 loc) · 1.4 KB

Algorithm

257. Binary Tree Paths

Description

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

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 class Solution {
     List<String> list=new ArrayList<>();
     public List<String> binaryTreePaths(TreeNode root) {
         if(root == null){
             return list;
         }
         String s = "";
         dfs(root,s);
         return list;
     }
     public void dfs(TreeNode root, String s){
         if(root.left==null && root.right==null){
             list.add(s+root.val);
             return;
         }
         if(root.left!=null){
             dfs(root.left, s+root.val+"->");
         }
         if(root.right!=null){
             dfs(root.right, s+root.val+"->");
         }
     }
 }

Discuss

深度优先遍历采用递归

广度优先遍历采用queue

Review

Tip

Share