[英]Print all the nodes in a binary tree which do not have sibling?
兄弟節點是具有相同父節點的節點。 在二叉樹中,最多只能有一個兄弟。 根本不應該打印為root不能有兄弟。
我已經為此編寫了代碼,該代碼在我迄今為止使用的所有測試用例中都運行良好,但是當我嘗試在網上判斷它時,大多數情況都出錯了。 雖然我已經盡力弄明白它是什么,但我無法弄清楚可能是什么錯誤。 此外,我無法為特定的測試用例進行干運行,因為我無法訪問它們。
public static void printNodesWithoutSibling(BinaryTreeNode<Integer> root) {
if(root==null)
return;
printNodesWithoutSibling(root.left);
printNodesWithoutSibling(root.right);
if(root.right==null && root.left!=null)
{
System.out.print(root.left.data+" ");
return;
}
else if(root.left==null && root.right!=null)
{
System.out.print(root.right.data+" ");
return;
}
}
您的代碼沒有考慮沒有正確兄弟的左孩子的情況。
確定節點是否具有兄弟節點所需的知識在其父節點中。
以下代碼段以預先的順序打印沒有兄弟節點的節點。 您可以輕松修改它是您需要的順序或后序。 代碼是用c ++編寫的,但我認為在java中重構不會有任何問題
void print_nodes_without_sibling(Node * root, bool no_sibling = false)
{
if (root == nullptr)
return;
if (no_sibling)
cout << root->key << endl;
print_nodes_without_sibling(root->left,
root->left != nullptr and root->right != nullptr);
print_nodes_without_sibling(root->right,
root->left != nullptr and root->right != nullptr);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.