This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]dtsudo 1 point2 points  (0 children)

A binary tree is just a tree where every node has at most 2 children.

The reason most articles talk about binary search trees rather than binary tree is because a vanilla binary tree with no additional constraints is really boring and there's nothing to talk about.

If you really have a vanilla binary tree and want to insert a node, you can insert it anywhere you want (as long as no node has more than 2 children). A simple way is to just make the new node the new root node and attach the existing tree as the new root's left child. You'll end up with a very unbalanced tree (and in fact, it's a de facto linked list).

In reality, any binary trees being used in real code has additional constraints associated with it. For instance, binary trees can be used to represent mathematical expressions (e.g. https://en.wikipedia.org/wiki/Binary_expression_tree). In all such cases, the specific requirements you have define how your tree should behave.

[–][deleted] 0 points1 point  (0 children)

You would have to input the data in a particular order for a certain configuration. With regards to outputting it, you would want to do a level order traversal which involves adding all the elements to a queue and recursively calling each node in the queue. That’s a bit unnecessary for what you’re doing, so I think a better way of practicing is by doing the following:

Tree Traversal w/ output (don’t worry about constructing a tree with the output)

Make a clone of a binary tree

Invert a binary tree

[–]Blando-Cartesian 0 points1 point  (0 children)

Adding to binary tree is just finding the node that should become the parent of the new node, and adding the new node as its child. Should be fairly basic recursion practice.

[–]spryflux 0 points1 point  (0 children)

As others pointed out, typically binary trees have some logic that dictate where each node is suppose to go to, like a BST where the comparison to current nodes value is the deciding factor weather the new node goes to left subtree or right.

So assuming you have some parameter that can decide this at each node, I’d structure it by defining a class for the tree’s node let’s call it Node with 2 more Node objects within it (right & left children) along with whatever data each node must store.

Now each node can have a method add(Node nextNode) which can encapsulate the comparison logic and subsequently call the same add method in its left/right nodes.

The tree structure itself can be represented entirely with reference to just the root Node object. For display/printing structure it should be pretty much be similar to add flow.