题意:
解题思路:
思路:
1. 变换操作:左子树变成根节点,根节点变成右子树,右子树变成左子树;
PHP代码实现:
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return TreeNode
*/
function upsideDownBinaryTree($root) {
if ($root == null || $root->left == null && $root->right == null) {
return $root;
}
$node = $this->upsideDownBinaryTree($root->left);
$root->left->left = $root->right;
$root->left->right = $root;
$root->left = null;
$root->right = null;
return $node;
}
}
GO代码实现:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func upsideDownBinaryTree(root *TreeNode) *TreeNode {
if root == nil || root.Left == nil && root.Right == nil {
return root
}
node := upsideDownBinaryTree(root.Left)
root.Left.Left = root.Right
root.Left.Right = root
root.Left = nil
root.Right = nil
return node
}