Okii honii 3ana problem esmo “ Binary Tree Paths” okiii Bahiii honii 3ana problem esmo…
- User
Okii honii 3ana problem esmo “ Binary Tree Paths” okiii
Bahiii honii 3ana problem esmo the “root” of a binary Tree , return all “root-to-leaf” paths In any order : Q- bahii honii 3ana definition of what is “leaf” ?
—> a leaf is a node with no children okii
Bahii honii 3ana “root” = [1,2,3,null,5]
—> donc honii 3ana problem mt3 enik ttl3 el path mt3 node and just print it okii
Bahii awl 7aje chnowa howa all the pathis in the Tree Path 1 : 1->2->5 // wsolna el leaf node twa okii Path 2 : 1 ->3 // wsolan el leaf node okii
Q- donc honi el trick hawaii enikk “traverse” the binary Tree , create the right string format str=”node1 → node2 → node2” okii and push it into the result list okii
For the “Traversal” part we use dfs okii Stack : okii For the string format we just “format “ it okii And to store it just append it to the result list okii
Q- dfs :
stack = [(root,””)] Result = [] While stack: node,s=stack.pop() current_string=”s”
Q- wait nsef 7je ntsw5er lzemn i check if the node is a leaf (yes or not ) :
codeIf is_leaf(node): result.append(current_string)Q- now let’s try continue the logic for me ? if node.right: stack.append(node,”->node.right.val”) If node.left: stack.append(node,”->node.left.val”) Return result
Q- chof honi awl iteration 3andii anii honii Q- mch a7sen w7da wle a5er w7eda hya Q- mais n7ebk tkon el pair programmer pattern for me and give me a good feedback okii Q- without given me the full slutoon oki
It sounds like you’re off to a solid start with the “Binary Tree Paths” problem, and I can tell you’re following a nice structured plan! You're handling the traversal with DFS and managing the path building with a stack-based approach. Here’s some feedback to consider:
Feedback
-
Path String Formatting: You’re using
current_string = s, which might not work as expected. Consider ifsincludes the whole path up to the current node, not just the immediate value. If not, think about updatingcurrent_stringto include thenode.valat each step before pushing toresult. -
DFS Traversal Order: You’re setting up the right traversal logic, where each time you encounter a node with children, you add the
leftandrightnodes to the stack along with the path so far. However, double-check yourstack.appendformat: when you appendnode.rightandnode.left, the strings might not be fully formatted yet. Ensure they properly concatenate the path so far.
-
- Assistant