Invert a binary tree.
反轉二叉樹
基本上二叉樹的玩意兒用遞歸都能做
For example
to
My Solution
(Java) Version 1 Time: 1ms:
簡單地遞歸然后調換左右子樹
/**
* 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;
}
root.left = invertTree(root.left);
root.right = invertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
(Java) Version 2 Time: 0ms (By anjani_sureshbhat):
有遞歸調用自然就有非遞歸調用倘是,這就是一個迭代的版本盏檐,然而我的迭代寫得并不好砾医,還要多看,當然還有一個很重要的就是迭代比遞歸快
/**
* 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;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode polled = q.poll();
if (polled.left != null || polled.right != null) {
TreeNode temp = polled.left;
polled.left = polled.right;
polled.right = temp;
if (polled.left != null) q.offer(polled.left);
if (polled.right != null) q.offer(polled.right);
}
}
return root;
}
}