zoukankan      html  css  js  c++  java
  • 669. 修剪二叉搜索树

    给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。

    solution:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* trimBST(TreeNode* root, int L, int R) {
    13         if(root == nullptr) return root;
    14         if(root->val > R) return trimBST(root->left,L,R);
    15         if(root->val < L) return trimBST(root->right,L,R);
    16         root->left = trimBST(root->left,L,R);
    17         root->right = trimBST(root->right,L,R);
    18         return root;
    19     }
    20 };
    View Code

     思路:递归,对当前节点的数值进行分析,分为四种情况:

    1.当前节点为空,返回当前节点

    2.当前节点比R大,则其左孩子继续递归进行

    3.当前节点比L小,则其右孩子继续递归进行

    4.当前节点在[L,R]范围内,则左右孩子分别进行递归。

  • 相关阅读:
    谷粒商城网关服务建立(七)
    谷粒商城Nacos配置(六)
    谷粒商城Nacos配置(五)
    Nacos入门
    谷粒商城心得二
    谷粒商城的快速开发(四)
    谷粒商城的快速开发(三)
    谷粒商城心得一
    谷粒商城的环境搭建(二)
    PowerDesigner16安装&破解
  • 原文地址:https://www.cnblogs.com/Swetchine/p/11355431.html
Copyright © 2011-2022 走看看