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

翻转二叉树

翻转一棵二叉树。

示例:

  1. 输入:
  2. 4
  3. / \
  4. 2 7
  5. / \ / \
  6. 1 3 6 9

输出:

  1. 4
  2. / \
  3. 7 2
  4. / \ / \
  5. 9 6 3 1

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

解题思路

递归法: 主要是遍历一下二叉树,将左边的值赋值给右边,遍历完也是交换完了。

迭代法: 将二叉树压入队列,然后循环队列,一个个节点弹出来,每个节点交换左右子树的值,迭代完毕也是交换完毕

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. * @return TreeNode
  14. */
  15. function invertTree($root) {
  16. if ($root == null) return null;
  17. // 保存右子树
  18. $rightTree = $root->right;
  19. // 交换左右子树的位置
  20. $root->right = $this->invertTree($root->left);
  21. $root->left = $this->invertTree($rightTree);
  22. return $root;
  23. }
  24. }

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. * @return TreeNode
  14. */
  15. function invertTree($root) {
  16. if ($root == null) return null;
  17. $queue = new SplQueue();
  18. $queue->enqueue($root);
  19. while (!$queue->isEmpty()) {
  20. $node = $queue->dequeue();
  21. list($node->left, $node->right) = [$node->right, $node->left];
  22. if ($node->left) {
  23. $queue->enqueue($node->left);
  24. }
  25. if ($node->right) {
  26. $queue->enqueue($node->right);
  27. }
  28. }
  29. return $root;
  30. }
  31. }

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