[英]Mirror Binary Search Tree using Recursion
在練習二叉搜索樹時尋求幫助。 我無法弄清楚我的代碼哪里出錯了,因為它似乎遵循通用遞歸格式。 可能與臨時節點或返回語句有關? 任何幫助將不勝感激。
public static Node < Integer > mirror(Node < Integer > root) {
if (root == null)
return null;
else {
mirror(root.left);
mirror(root.right);
Node temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
首先,您似乎沒有為將屬於鏡像樹的節點分配 memory。 注意指令
Node temp;
不在堆中分配,而是在堆棧中分配。 當 function 返回時,此 memory 將被釋放,並且您在那里存儲的任何內容都沒有意義。
其次,您似乎沒有很清楚的遍歷模式,我認為是因為線
root.right = temp;
構成一種不對稱。
這是一種獲取使用前序模式的鏡像二叉樹的方法(在 C++ 偽代碼中):
Node * mirror(Node * root)
{
if root == NULL
return NULL;
Node * mirror_root = new Node;
mirror_root->left = mirror(root->right); // here is where the mirroring happens
mirror_root->right = mirror(root->left);
return mirror_root;
}
您可以嘗試執行相同的操作,以后序或中序分配節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.