# 226. Invert Binary Tree (非常簡單的題目) Java final object

May 13, 2017 · 3 min read

```public class Solution {
public TreeNode invertTree(TreeNode root) {

if (root == null) {
return null;
}final Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);while(!queue.isEmpty()) {
final TreeNode node = queue.poll();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
return root;
}
}```

```public class Solution {
public TreeNode invertTree(TreeNode root) {

if (root == null) {
return null;
}final Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);

while(!stack.isEmpty()) {
final TreeNode node = stack.pop();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;

if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
return root;
}
}```

ob will not be able to reference any other object : final keyword.

It can not be reassigned. But you can change its internals (it is mutable, if it was originally). So this works :

``````final A ob = new A();
ob.setI(6)``````

but this doesn’t :

``````final A ob = new A();
ob = new A();``````

Written by