Editing
Binary Trees
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Example: Binary Search Tree == A binary search tree is a binary tree with the additional property that the value of each node is greater than or equal to the values of all nodes in its left subtree and less than or equal to the values of all nodes in its right subtree. Here is a C++ example of a simple binary search tree: <pre> #include <iostream> struct TreeNode { int value; TreeNode * left; TreeNode * right; TreeNode(int val): value(val), left(nullptr), right(nullptr) {} }; class BinaryTree { public: TreeNode * root; BinaryTree(): root(nullptr) {} void insert(int data) { if (root == nullptr) { root = new TreeNode(data); } else { insertHelper(root, data); } } private: void insertHelper(TreeNode * node, int data) { if (data < node -> value) { if (node -> left == nullptr) { node -> left = new TreeNode(data); } else { insertHelper(node -> left, data); } } else { if (node -> right == nullptr) { node -> right = new TreeNode(data); } else { insertHelper(node -> right, data); } } } }; int main() { BinaryTree tree; tree.insert(5); tree.insert(3); tree.insert(7); tree.insert(1); tree.insert(4); tree.insert(6); tree.insert(8); // The tree structure is now: // 5 // / \ // 3 7 // / \ / \ // 1 4 6 8 return 0; } </pre> In this example, we create a binary search tree and insert nodes with the values 5, 3, 7, 1, 4, 6, and 8. The structure of the tree is as shown in the comments.
Summary:
Please note that all contributions to Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
My wiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information