反轉二叉樹。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