Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1分析:又是二叉树的问题,很多二叉树的问题可以用递归算法来解决。先判断当前结点是否为空,此为递归的出口;接下来交换左孩子和右孩子的位置,分别以左孩子和右孩子为结点,继续递归循环判断是否有左孩子或者右孩子,进而继续交换位置。
Java代码如下:
/**
* 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;
}
// 递归方法
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
root.right = invertTree(root.right);
root.left = invertTree(root.left);
return root;
}
}
解法二:非递归方式
本方法适用于无返回值的解法
public void invertTree(TreeNode root) {
if(root == null) {
return;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
TreeNode temp = null;
list.add(root);
while(list.size() != 0){
TreeNode node = list.removeFirst();
temp = node.left;
node.left = node.right;
node.right = temp;
if(node.left != null){
list.add(node.left);
}
if(node.right != null){
list.add(node.right);
}
}
}