layout: posttitle: PHP 实现修剪二叉树
subtitle: PHP 实现修剪二叉树
date: 2020-07-07
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode
- 修剪二叉树

修剪二叉树

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

示例 1:

  1. 输入:
  2. 1
  3. / \
  4. 0 2
  5. L = 1
  6. R = 2
  7. 输出:
  8. 1
  9. \
  10. 2

示例 2:

  1. 输入:
  2. 3
  3. / \
  4. 0 4
  5. \
  6. 2
  7. /
  8. 1
  9. L = 1
  10. R = 3
  11. 输出:
  12. 3
  13. /
  14. 2
  15. /
  16. 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trim-a-binary-search-tree

解题思路

递归遍历二叉树,进行特殊情况的判断,如果 < $L,则只遍历他的右子树,如果 > $R,则只遍历左子树,其他在区间内的相当于重新赋值,无需额外处理。

php 代码

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param TreeNode $root
  13. * @param Integer $L
  14. * @param Integer $R
  15. * @return TreeNode
  16. */
  17. function trimBST($root, $L, $R) {
  18. if ($root == null) {
  19. return $root;
  20. }
  21. if ($root->val < $L) {
  22. return $this->trimBST($root->right, $L, $R);
  23. }
  24. if ($root->val > $R) {
  25. return $this->trimBST($root->left, $L, $R);
  26. }
  27. $root->left = $this->trimBST($root->left, $L, $R);
  28. $root->right = $this->trimBST($root->right, $L, $R);
  29. return $root;
  30. }
  31. }

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券