问题描述:
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
思路:
基础题目,提供两个版本:递归和非递归版本
JAVA代码:
递归版本:
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) {
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
非递归版本:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) {
return null;
}
Stack<TreeNode> tnroot = new Stack<TreeNode>();
tnroot.push(root);
while(!tnroot.isEmpty()){
TreeNode cur = tnroot.pop();
TreeNode temp = cur.left;
cur.left = cur.right;
cur.right = temp;
if(cur.left != null){
tnroot.push(cur.left);
}
if(cur.right != null){
tnroot.push(cur.right);
}
}
return root;
}
}