C++ 中修剪给定二叉树的程序
假设我们有一棵二叉树,其中每个节点的值要么是 0,要么是 1。我们必须找到同一棵树,其中不包含 1 的每个子树都被删除。因此,如果树如下:
为解决这个问题,我们将按照以下步骤操作:
定义一个递归方法 solve(),它将采用节点。此方法如下:
如果节点为 null,则返回 null
节点左侧:= solve(节点左侧)
节点右侧:=solve(节点右侧)
如果节点左侧为 null 且节点右侧也为 null,并且节点值为 0,则返回 null
返回节点
让我们看看以下实现以获得更好的理解:
示例
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void inorder(TreeNode *root){ if(root){ inorder(root->left); cout << root->val << ", "; inorder(root->right); } } class Solution { public: TreeNode* pruneTree(TreeNode* node) { if(!node)return NULL; node->left = pruneTree(node->left); node->right = pruneTree(node->right); if(!node->left && !node->right && !node->val){ return NULL; } return node; } }; main(){ TreeNode *root = new TreeNode(1); root->left = new TreeNode(1); root->right = new TreeNode(0); root->left->left = new TreeNode(1); root->left->right = new TreeNode(1); root->right->left = new TreeNode(0); root->right->right = new TreeNode(1); root->left->left->left = new TreeNode(0); Solution ob; inorder(ob.pruneTree(root)); }
输入
TreeNode *root = new TreeNode(1); root−>left = new TreeNode(1); root−>right = new TreeNode(0); root−>left−>left = new TreeNode(1); root−>left−>right = new TreeNode(1); root−>right−>left = new TreeNode(0); root−>right−>right = new TreeNode(1); root−>left−>left−>left = new TreeNode(0);
输出
1, 1, 1, 1, 0, 1,
广告