C++ 中的二叉树剪枝


假设我们有两个二叉树的头节点 root,其中每个节点的值是 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 insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         temp->left = new TreeNode(val);
         return;
      }else{
         q.push(temp->left);
      }
      if(!temp->right){
         temp->right = new TreeNode(val);
         return;
      }else{
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
void tree_level_trav(TreeNode*root){
   if (root == NULL) return;
   cout << "[";
   queue<TreeNode *> q;
   TreeNode *curr;
   q.push(root);
   q.push(NULL);
   while (q.size() > 1) {
      curr = q.front();
      q.pop();
      if (curr == NULL){
         q.push(NULL);
      } else {
         if(curr->left)
            q.push(curr->left);
         if(curr->right)
            q.push(curr->right);
         if(curr == NULL){
            cout << "null" << ", ";
         }else{
            cout << curr->val << ", ";
         }  
      }
   }
   cout << "]"<<endl;
}
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(){
   vector<int> v = {1,1,0,1,1,0,1,0};
   TreeNode *root = make_tree(v);
   Solution ob;
   tree_level_trav(ob.pruneTree(root));
}

输入

[1,1,0,1,1,0,1,0]

输出

[1, 1, 0, 1, 1, 1, ]

更新时间:2020-05-02

533 次观看

开启您的 职业

通过完成课程获得认证

开始学习
广告
© . All rights reserved.