zoukankan      html  css  js  c++  java
  • Leetcode669-Trim a Binary Search Tree-Easy

    题目:Trim a Binary Search Tree

    Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

    Example 1:

    Input: 
        1
       / 
      0   2
    
      L = 1
      R = 2
    
    Output: 
        1
          
           2
    

    Example 2:

    Input: 
        3
       / 
      0   4
       
        2
       /
      1
    
      L = 1
      R = 3
    
    Output: 
          3
         / 
       2   
      /
     1


     思路:
    BST的特性:left < root < right
    case 1: 如果root.val < L, 则返回修剪后的右子树 (把root 和左子树都裁掉:左子树的所有值一定小于L)
    case 2: 如果root.val > R, 则返回修剪后的左子树 (裁掉root 和 右子树)
    case 3: 如果 root.val 在范围内,那么保留root结点本身, 并且root.left = 修剪后的左子树, root.right = 修剪后的右子树。
     
    代码:
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public TreeNode trimBST(TreeNode root, int L, int R) {
            if (root == null) return root;
            
            if (root.val < L) return trimBST(root.right, L, R);
            
            if (root.val > R) return trimBST(root.left, L, R);
            // 要把修剪过后的左右子树赋值给root.left root.right
            root.left = trimBST(root.left, L, R);
            root.right = trimBST(root.right, L, R);
            return root;
        }
    }
  • 相关阅读:
    ListView Item 点击展开隐藏问题
    01背包基础 (杭电2602)
    实现一个简单的语音聊天室(多人语音聊天系统)
    Tomcat全攻略
    Linux pipe函数
    从网页抓取数据的一般方法
    华为的面试经历
    微软2014校园招聘笔试试题
    C++ 虚函数表解析
    unity3d 改动gui label颜色,定义颜色需除以256
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/13437229.html
Copyright © 2011-2022 走看看