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

JAVA CODE

The document defines a Java class 'TreeMaze' that includes two methods: 'canReachLeaf' and 'leafPath'. 'canReachLeaf' checks if there is a path to a leaf node in a binary tree, while 'leafPath' retrieves the path to the first leaf node found. Both methods handle cases where the node is null or has a value of zero.

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)
0 views

JAVA CODE

The document defines a Java class 'TreeMaze' that includes two methods: 'canReachLeaf' and 'leafPath'. 'canReachLeaf' checks if there is a path to a leaf node in a binary tree, while 'leafPath' retrieves the path to the first leaf node found. Both methods handle cases where the node is null or has a value of zero.

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

import java.util.

ArrayList;

// Definition of TreeNode:
// public class TreeNode {
//
// int val;
// TreeNode left;
// TreeNode right;
//
// public TreeNode(int val) {
// this.val = val;
// this.left= null;
// this.right = null;
// }
// }

public class TreeMaze {

public boolean canReachLeaf(TreeNode 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;
}

public boolean leafPath(TreeNode root, ArrayList<Integer> path) {


if (root == null || root.val == 0) {
return false;
}
path.add(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