初めてバイナリ ツリーのポストオーダー トラバーサルの問題を解決するとき、ノードを格納するために 1 つのスタックのみを使用し、結果として 1 つのリストを使用します。したがって、時間計算量は明らかに N^2 です。しかし、2 つのスタックを使用する場合、時間の計算量は N に単純化できます。
プレオーダートラバーサルに関しては、1スタックで十分だと思います。しかし、私のソリューションの実行時間はまだ中間レベルにとどまっています。
それで、それを改善するための解決策はありますか?以下は私のコードです:
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> nodes = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
if (root == null)
return result;
nodes.push(root);
while (!nodes.isEmpty()) {
TreeNode temp = nodes.pop();
result.add(temp.val);
if (temp.right != null) {
nodes.push(temp.right);
}
if (temp.left != null) {
nodes.push(temp.left);
}
}
return result;
}
}
ありがとうございました!