226. 翻转二叉树 各种解法
2019-01-05 本文已影响13人
如沙雨下
题目描述:
翻转一棵二叉树。
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
一.JAVA迭代
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
return root;
}
}
二.JAVA递归
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
root.left=invertTree(root.left);
root.right=invertTree(root.right);
TreeNode temp =root.left;
root.left=root.right;
root.right=temp;
return root;
}
}
三.Python
class Solution:
def invertTree(self, root):
if root :
root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
return root