我們來考慮一下從其中序遍歷和後序遍歷構造二叉搜索樹的問題。現在在遞歸實現中,我會這樣做:如何將遞歸函數模型模擬爲帶有堆棧的迭代函數模型?
node.left = recursive(start,mid-1); node.right =遞歸(mid + 1,end);
現在我將如何去實現這與堆棧?一旦從堆棧彈出一個節點,我就不能回到它。這種迭代方法僅適用於遍歷嗎?
這是整個代碼,其中_constructInPost是遞歸的要點:
Node<T> _constructInPost (List<T> in, List<T> post) {
if (in.size() == 0)
return null;
Node<T> root = new Node <T>(post.get(post.size()-1));
int index = 0;
for (; index < post.size(); index++) {
if (in.get(index) == root.data)
break;
}
root.left = _constructInPost (in.subList(0, index), post.subList(0, index));
root.right = _constructInPost (in.subList(index+1, in.size()), post.subList(index, post.size()-1));
return root;
}
可以隨時替補遞歸與迭代,因爲這是操作系統做背景,你的整個代碼是什麼? – 2014-09-11 05:32:52
我編輯了描述。 – shrinidhisondur 2014-09-11 05:36:30