0% found this document useful (0 votes)
2 views

Javascript Code

The document defines a TreeNode class for creating binary tree nodes and two functions: canReachLeaf and leafPath. The canReachLeaf function checks if there is a path to a leaf node in the tree where all node values are non-zero. The leafPath function attempts to find a path to a leaf node, storing the path values, and returns true if successful.

Uploaded by

utkarsh deepak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Javascript Code

The document defines a TreeNode class for creating binary tree nodes and two functions: canReachLeaf and leafPath. The canReachLeaf function checks if there is a path to a leaf node in the tree where all node values are non-zero. The leafPath function attempts to find a path to a leaf node, storing the path values, and returns true if successful.

Uploaded by

utkarsh deepak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class TreeNode {

constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}

function canReachLeaf(root) {
if (root == null || root.val == 0) {
return false;
}
if (root.left == null && root.right == null) {
return true;
}
if (canReachLeaf(root.left)) {
return true;
}
if (canReachLeaf(root.right)) {
return true;
}
return false;
}

function leafPath(root, path) {


if (root == null || root.val == 0) {
return false;
}
path.push(root.val);

if (root.left == null && root.right == null) {


return true;
}
if (leafPath(root.left, path)) {
return true;
}
if (leafPath(root.right, path)) {
return true;
}
path.remove(path.size() - 1);
return false;
}

You might also like