简体   繁体   中英

Print all the nodes in a binary tree which do not have sibling?

A sibling is a node that has same parent. In a Binary Tree, there can be at most one sibling. Root should not be printed as root cannot have a sibling.

I have written code for this which works fine in all the Testcases which I have used so far but when I tried to submit it in online judge it got wrong for most of the cases. I am not able to figure out what could be the bug although I have tried my best to figure out what it is. Also I can not dry run for that particular Testcases as I do not have access to them.

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;
        }
}

Your code does not take into account the case for a left child without a right sibling.

The required knowledge for determining if a node has a sibling is in its parent.

The following code snippet prints, in preorder, the nodes that do not have a sibling. You could easily modify it is you require it in inorder or postorder. The code is written in c++, but I think that you will not have any problem for refactoring in 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM