反转二叉树。node
相似反转两个变量,先把左右子树存进单独的变量,再相互覆盖左右子树。
并对子树进行相同的操做。this
<?php /** * Definition for a binary tree node. * class TreeNode { * public $val = null; * public $left = null; * public $right = null; * function __construct($value) { $this->val = $value; } * } */ class Solution { /** * @param TreeNode $root * @return TreeNode */ function invertTree($root) { $left = $root->left; $right = $root->right; $root->left = $right; $root->right = $left; if($root->left){ $this->invertTree($root->left); } if($root->right){ $this->invertTree($root->right); } return $root; } }
若以为本文章对你有用,欢迎用爱发电资助。.net