A nice binary tree problem by using recursion

--

Recursion is a powerful method if you know how to use it properly.

A nice binary tree problem can be found:

814. Binary Tree Pruning

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* pruneTree(TreeNode* root) {
if (root == nullptr) return nullptr;
root -> left = pruneTree(root -> left);
root -> right = pruneTree(root -> right);
if (root -> val == 1 || root -> left || root -> right)return root;
return nullptr;
}
};

Pretty nice, right? Thanks for reading.

--

--