2015-07-21 34 views
2

雖然編碼關於對本文給出了二叉搜索樹的問題,我想出了以下情況:另一個類初始化類的方式

public class TreeNode { 
    int val; 
    TreeNode left; 
    TreeNode right; 
    TreeNode(int x) { val = x; } 
} 

public class Solution { 
    public List<Integer> inorderTraversal (TreeNode root) { 
// the variables below are defined by myself. 

     Stack <TreeNode> stack = new Stack<TreeNode>(); 
     ArrayList<Integer> res = new ArrayList<Integer>(); 
     TreeNode curr = root; 
     ... 
    } 
} 

在最後一行,我定義了一個TreeNode並使它等於root。但如果我寫爲

TreeNode curr = new TreeNode() 

編譯器產生一個錯誤。我不知道爲什麼我不能以這種方式將TreeNode定義爲臨時變量。

回答

4

TreeNode類不具有一個無參數的構造函數。

既然你已經定義了一個構造函數int參數編譯器將不會爲您創建一個默認的構造函數。

是這樣的(假設它是有道理的),將工作:

TreeNode cust = new TreeNode(someIntValue); 
+0

哦!得到它了 !非常感謝你! – beepretty

2

樹節點構造函數的參數整數X,所以如果你只寫 「樹節點CURR =新的TreeNode();」,則將是一個錯誤。所有你需要做的是爲參數添加一個int。

解決方案:「TreeNode curr = new TreeNode(4);」

只需添加任何int值。

+0

非常感謝! – beepretty

2

Java允許你只使用的情況下,默認的構造函數(與無參數構造函數),你沒有明確地在類中創建你自己的構造函數。 一旦你創建自己的構造函數,就你的情況TreeNode(int x) { val = x; }你不能再使用該類的默認構造函數。

+0

是啊!非常感謝! – beepretty