題目描述:
翻轉(zhuǎn)一棵二叉樹(shù)嗜价。
谷歌:我們90%的工程師使用您編寫(xiě)的軟件(Homebrew),但是您卻無(wú)法在面試時(shí)在白板上寫(xiě)出翻轉(zhuǎn)二叉樹(shù)這道題,這太糟糕了。
一.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