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

Bear熊
Bear熊
May 13, 2017 · 3 min read

這題大意很簡單,總之就是把一個樹翻轉過來

但是我一開始把她想得有點複雜化了….所以沒解出來(羞)

探索樹有兩種方法 DFS ( STACK ) 跟 BFS ( QUEUE )

以下是 BFS 的方法

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;
    }
}

以下是DFS 值得注意的是 他用的是 Deque 好像用法可以比 stack多元一點 不過此粒子中其實是一樣的意思

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;
    }
}

值得注意的是 他有用到 final Object

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();

意思是說他的指標位置已經不能再更改了!

但是其實他指到的內容物(attribute)還是可以更改的

值得注意!

Bear熊

Written by

Bear熊

A software engineer