題目
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
我在 Eclipse試著解這題,但是在我註解的那2行出錯,請問要怎麼改才會跑出結果?
(從此行以下開始)
import java.util.LinkedList;
import java.util.Queue;
// import javax.swing.tree.TreeNode;
public class _MaxDepth_BinaryTree {
public static void main(String[] args) {
TreeNode root = null;
int depth = 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
depth++;
int qLen = q.size();
for (int i = 0; i < qLen; i++) {
TreeNode node = q.poll();
if (node.left != null) q.offer(node.left); //這行.left出錯
if (node.right != null) q.offer(node.right); //這行.right出錯
}
}
return;
System.out.println(depth);
}
}
喔喔,感謝回答,可是要如何修改才是正確的呢?
因為照下面寫結果跑出另一個錯誤 java.lang.NullPointerException
class Node{
Node left, right;
int value;
Node(int value){
left=right=null;
this.value = value;
}
}
抄這個