Top Banner
Binary Tree Basics
22

Lecture 9: Binary tree basics

Jun 29, 2015

Download

Engineering

Vivek Bhargav

This slide is part of course designed for placement preparation for students of IIT Guwahati.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lecture 9: Binary tree basics

Binary Tree Basics

Page 2: Lecture 9: Binary tree basics

Binary Tree Definition

• Every node has at most two children a left child and a right child.

• Root - the top most node in a tree.

Page 3: Lecture 9: Binary tree basics
Page 4: Lecture 9: Binary tree basics

A Basic Tree Structure

Page 5: Lecture 9: Binary tree basics

Leaf

• A node having no child is a leaf.

Page 6: Lecture 9: Binary tree basics

Depth of a node

• The length of the path from the root to the node.

• Depth(root)=0

Page 7: Lecture 9: Binary tree basics

Height of the tree

• The height of a node is the length of the longest downward path between the node and a leaf + 1.

• The height of a node is the length of the longest downward path between the root and a leaf +1.

Page 8: Lecture 9: Binary tree basics

Depth and height

Page 9: Lecture 9: Binary tree basics

Full Binary Tree

• Every node has 2 children except the leaves.

Page 10: Lecture 9: Binary tree basics

Complete Binary Tree

• A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Page 11: Lecture 9: Binary tree basics

• A fully complete binary tree has n nodes what is the height of the tree?

O(log n)

Page 12: Lecture 9: Binary tree basics

• A fully complete binary tree has n nodes what are the number of leaves in the tree?

Ceil(n/2)

Page 13: Lecture 9: Binary tree basics

Implementation

Page 14: Lecture 9: Binary tree basics

Search an element in binary tree

Page 15: Lecture 9: Binary tree basics

Sum of all the nodes of the tree

Page 16: Lecture 9: Binary tree basics

Inorder traversal

• Visit the left subtree first• Visit the node.• Visit the right subtree.

Page 17: Lecture 9: Binary tree basics

Code

Page 18: Lecture 9: Binary tree basics

Postorder traversal

• Visit the left subtree first• Visit the right subtree• Visit the node.

Page 19: Lecture 9: Binary tree basics

Preorder traversal

• Visit the node.• Visit the left subtree first• Visit the right subtree.

Page 20: Lecture 9: Binary tree basics

Vector

vector<int> a;a.push_back(value);cout<<a[i]<<endl;Accessing the pushed back value similar to an

array.(REST READ FROM NET)