Lecture 9: Binary tree basics

Post on 29-Jun-2015

130 views 3 download

Tags:

description

This slide is part of course designed for placement preparation for students of IIT Guwahati.

Transcript of Lecture 9: Binary tree basics

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.

A Basic Tree Structure

Leaf

• A node having no child is a leaf.

Depth of a node

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

• Depth(root)=0

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.

Depth and height

Full Binary Tree

• Every node has 2 children except the leaves.

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.

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

O(log n)

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

Ceil(n/2)

Implementation

Search an element in binary tree

Sum of all the nodes of the tree

Inorder traversal

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

Code

Postorder traversal

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

Preorder traversal

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

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)