0% found this document useful (0 votes)
2 views1 page

C - Code

The document defines a TreeNode class and two functions, canReachLeaf and leafPath, for traversing a binary tree. canReachLeaf checks if there is a path to a leaf node with a non-zero value, while leafPath constructs the path to the first reachable leaf node. Both functions utilize recursion to navigate through the tree structure.

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 views1 page

C - Code

The document defines a TreeNode class and two functions, canReachLeaf and leafPath, for traversing a binary tree. canReachLeaf checks if there is a path to a leaf node with a non-zero value, while leafPath constructs the path to the first reachable leaf node. Both functions utilize recursion to navigate through the tree structure.

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

#include <vector>

using std::vector;

class TreeNode {
public:
int val_;
TreeNode* left = nullptr;
TreeNode* right = nullptr;

TreeNode(int val) {
val_ = val;
}
};

bool canReachLeaf(TreeNode *root) {


if (!root || root->val_ == 0) {
return false;
}
if (!root->left && !root->right) {
return true;
}
if (canReachLeaf(root->left)) {
return true;
}
if (canReachLeaf(root->right)) {
return true;
}
return false;
}

bool leafPath(TreeNode* root, vector<int>* path) {


if (!root || root->val_ == 0) {
return false;
}
path->push_back(root->val_);

if (!root->left && !root->right) {


return true;
}
if (leafPath(root->left, path)) {
return true;
}
if (leafPath(root->right, path)) {
return true;
}
path->pop_back();
return false;
}

You might also like