题意:

image.png

解题思路:

  1. 思路:
  2. 1. 变换操作:左子树变成根节点,根节点变成右子树,右子树变成左子树;

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($val = 0, $left = null, $right = null) {
  8. * $this->val = $val;
  9. * $this->left = $left;
  10. * $this->right = $right;
  11. * }
  12. * }
  13. */
  14. class Solution {
  15. /**
  16. * @param TreeNode $root
  17. * @return TreeNode
  18. */
  19. function upsideDownBinaryTree($root) {
  20. if ($root == null || $root->left == null && $root->right == null) {
  21. return $root;
  22. }
  23. $node = $this->upsideDownBinaryTree($root->left);
  24. $root->left->left = $root->right;
  25. $root->left->right = $root;
  26. $root->left = null;
  27. $root->right = null;
  28. return $node;
  29. }
  30. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func upsideDownBinaryTree(root *TreeNode) *TreeNode {
  10. if root == nil || root.Left == nil && root.Right == nil {
  11. return root
  12. }
  13. node := upsideDownBinaryTree(root.Left)
  14. root.Left.Left = root.Right
  15. root.Left.Right = root
  16. root.Left = nil
  17. root.Right = nil
  18. return node
  19. }