Binary Tree Paths - Tree - Easy - LeetCode
💻 coding

Binary Tree Paths - Tree - Easy - LeetCode

1 min read 167 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to return all root-to-leaf paths in a binary tree as strings.
  • 2A leaf node is defined as a node with no children.
  • 3The algorithm uses backtracking with a time complexity of O(2^n) and space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to return all root-to-leaf paths in a binary tree as strings."

Binary Tree Paths - Tree - Easy - LeetCode

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 public IList<string> BinaryTreePaths(TreeNode root) {
 var result = new List<string>();
 var str = new List<int>();
 if(root==null){
 return result;
 }
 
 Helper(root,str,result);
 return result;
 }
 
 private void Helper(TreeNode root,List<int> str, List<string> result){
 if(root == null){
 return;
 }
 
 str.Add(root.val);
 
 if(root.left == null && root.right == null){
 var sb = new StringBuilder();
 for(int i=0;i<str.Count()-1;i++){
 sb.Append(str[i]+"->");
 }
 if(str.Count()>0){
 sb.Append(str[str.Count()-1]);
 }
 result.Add(sb.ToString());
 }
 
 Helper(root.left, str, result); 
 Helper(root.right, str, result);
 str.RemoveAt(str.Count()-1);
 }
}

Time Complexity: O(2^n) we are doing backtracking

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 6 October 2020 · 1 min read · 167 words

Part of AskGif Blog · coding

You might also like