binary tree construction from preorder - algorithm

This is an Amazon interview question. Can any one give an algorithm to do this?
There is a binary tree with the following properties:
All of its inner node have the value 'N', and all the leaves have the value 'L'.
Every node either has two children or has no child.
Given its preorder, construct the tree and return the root node.

Since it is guaranteed that each internal node has exactly 2 children, we can simply build the tree recursively using that.
We call our function with the input provided, and it examines the first character it got. If it is a leaf node, it just returns a leaf. If it is an internal node, it just calls itself for the left and right subtrees and returns the tree formed using the node as root and the left and right subtrees as its left and right children.
Code follows (in Python). Note, I am using tuples to represent node, so the tree is a tuple of tuples.
#! /usr/bin/env python
from collections import deque
def build_tree(pre_order):
root=pre_order.popleft()
if root=='L':
return root
else:
return (root,build_tree(pre_order),build_tree(pre_order))
if __name__=='__main__':
print build_tree(deque("NNLLL"))
Edit: Code in Java
import java.util.*;
class Preorder{
public static Node buildTree(List<Character> preorder){
char token=preorder.remove(0);
if (token=='L'){
return new Node(token,null,null);
}
else{
return new Node(token,buildTree(preorder),buildTree(preorder));
}
}
public static void main(String args[]){
List<Character> tokens=new LinkedList<Character>();
String input="NNLLL";
for(int i=0;i<input.length();i++) tokens.add(input.charAt(i));
System.out.println(buildTree(tokens));
}
}
class Node{
char value;
Node left,right;
public Node(char value, Node left, Node right){
this.value=value;
this.left=left;
this.right=right;
}
public String toString(){
if (left==null && right==null){
return "("+value+")";
}
else{
return "("+value+", "+left+", "+right+")";
}
}
}

I can think of a recursive algorithm.
head = new node.
remove first character in preorderString
Invoke f(head, preorderString)
Recursive function f(node, s)
- remove first char from s, if L then attach to node as leaf.
else create a nodeLeft, attach to node, invoke f(nodeLeft, s)
- remove first char from s, if L then attach to node as leaf.
else create a nodeRight, attach to node, invoke f(nodeRight, s)

I think the key point is to realize that there are three possibilities for the adjacent nodes: NN, NL?, L? (``?'' means either N or L)
NN: the second N is the left child of the first N, but we don't know what the right child of the first N is
NL?: the second N is the left child of the first N, and the right child of the first N is ?
L?: ? is the right child of STACK top
A STACK is used because when we read a node in a preorder sequence, we don't know where its right child is (we do know where its left child is, as long as it has one). A STACK stores this node so that when its right child appears we can pop it up and finish its right link.
NODE * preorder2tree(void)
{
NODE * head = next_node();
NODE * p = head;
NODE * q;
while (1) {
q = next_node();
if (!q)
break;
/* possibilities of adjacent nodes:
* NN, NL?, L?
*/
if (p->val == 'N') {
p->L = q;
if (q->val == 'N') { /* NN */
push(p);
p = q;
} else { /* NL? */
q = next_node();
p->R = q;
p = q;
}
} else { /* L? */
p = pop();
p->R = q;
p = q;
}
}
return head;
}
The code above was tested using some simple cases. Hopefully it's correct.

Here is the java program::
import java.util.*;
class preorder_given_NNNLL
{
static Stack<node> stk = new Stack<node>();
static node root=null;
static class node
{
char value;
node left;
node right;
public node(char value)
{
this.value=value;
this.left=null;
this.right=null;
}
}
public static node stkoper()
{
node posr=null,posn=null,posl=null;
posr=stk.pop();
if(stk.empty())
{
stk.push(posr);
return null;
}
else
posl=stk.pop();
if(stk.empty())
{
stk.push(posl);
stk.push(posr);
return null;
}
else
{
posn=stk.pop();
}
if( posn.value == 'N' && posl.value == 'L' && posr.value == 'L')
{
root = buildtree(posn, posl, posr);
if(stk.empty())
{
return root;
}
else
{
stk.push(root);
root=stkoper();
}
}
else
{
stk.push(posn);
stk.push(posl);
stk.push(posr);
}
return root;
}
public static node buildtree(node posn,node posl,node posr)
{
posn.left=posl;
posn.right=posr;
posn.value='L';
return posn;
}
public static void inorder(node root)
{
if(root!=null)
{
inorder(root.left);
if((root.left == null) && (root.right == null))
System.out.println("L");
else
System.out.println("N");
inorder(root.right);
}
}
public static void main(String args[]){
String input="NNNLLLNLL";
char[] pre = input.toCharArray();
for (int i = 0; i < pre.length; i++)
{
node temp = new node(pre[i]);
stk.push(temp);
root=stkoper();
}
inorder(root);
}
}

The construct function does the actual tree construction. The code snippet is the solution for the GeeksforGeeks question that you mentioned as above.
struct Node*construct(int &index, Node*root, int pre[], int n, char preLN[])
{
Node*nodeptr;
if(index==n)
{
return NULL;
}
if(root==NULL)
{
nodeptr = newNode(pre[index]);
}
if(preLN[index]=='N')
{
index = index+1;
nodeptr->left = construct(index, nodeptr->left, pre,n,preLN);
index = index+1;
nodeptr->right = construct(index, nodeptr->right,pre,n,preLN);
return nodeptr;
}
return nodeptr;
}
struct Node *constructTree(int n, int pre[], char preLN[])
{
int index =0;
Node*root = construct(index,NULL,pre,n,preLN);
return root;
}
Points to Note:
Index has been declared a reference variable so that on returning back to the parent node, the function starts constructing the tree from the overall most recent value of index and not the value of index as possessed by the function when initially executing the call.
Different values of index for right and left subtrees since preorder traversal follows Root, Left ,Right sequence of nodes.
Hope it Helps.

Related

SINGLE Recursive function for Print/Fetch kth smallest element in Binary search tree

I am trying to print the kth smallest element in an BST.
The first solution is using in-order traversal.
Next solution is finding the index of the current node by calculation the size of its left subtree.
Complete algo:
Find size of left subtree:
1.If size = k-1, return current node
2.If size>k return (size-k)th node in right subtree
3.If size<k return kth node in left subtree
This can be implemented using a separate count function which looks something like
public class Solution {
public int kthSmallest(TreeNode root, int k) {
//what happens if root == null
//what happens if k > total size of tree
return kthSmallestNode(root,k).val;
}
public static TreeNode kthSmallestNode(TreeNode root,int k){
if(root==null) return root;
int numberOfNodes = countNodes(root.left);
if(k == numberOfNodes ) return root;
if(k<numberOfNodes ) return kthSmallestNode(root.left,k);
else return kthSmallestNode(root.right,k-numberOfNodes );
}
private static int countNodes(TreeNode node){
if(node == null) return 0;
else return 1+countNodes(node.left)+countNodes(node.right);
}
}
But I see that we count the size for same trees multiple times, so one way is to maintain an array to store thes sizes like the DP way.
But I want to write a recursive solution for this.And here is the code I have written.
class Node {
int data;
Node left;
Node right;
public Node(int data, Node left, Node right) {
this.left = left;
this.data = data;
this.right = right;
}
}
public class KthInBST
{
public static Node createBST(int headData)
{
Node head = new Node(headData, null, null);
//System.out.println(head.data);
return head;
}
public static void insertIntoBst(Node head, int data)
{
Node newNode = new Node(data, null, null);
while(true) {
if (data > head.data) {
if (head.right == null) {
head.right = newNode;
break;
} else {
head = head.right;
}
} else {
if (head.left == null) {
head.left = newNode;
break;
} else {
head = head.left;
}
}
}
}
public static void main(String[] args)
{
Node head = createBST(5);
insertIntoBst(head, 7);
insertIntoBst(head, 6);
insertIntoBst(head, 2);
insertIntoBst(head, 1);
insertIntoBst(head, 21);
insertIntoBst(head, 11);
insertIntoBst(head, 14);
insertIntoBst(head, 3);
printKthElement(head, 3);
}
public static int printKthElement(Node head, int k)
{
if (head == null) {
return 0;
}
int leftIndex = printKthElement(head.left, k);
int index = leftIndex + 1;
if (index == k) {
System.out.println(head.data);
} else if (k > index) {
k = k - index;
printKthElement(head.right, k);
} else {
printKthElement(head.left, k);
}
return index;
}
}
This is printing the right answer but multiple times, I figured out why it is printing multiple times but not understanding how to avoid it.
And also If I want to return the node instead of just printing How do I do it?
Can anyone please help me with this?
Objective:
Recursively finding the kth smallest element in a binary search tree and returning the node corresponding to that element.
Observation:
The number of elements smaller than the current element is the size of the left subtree so instead of recursively calculating its size, we introduce a new member in class Node, that is, lsize which represents the size of the left subtree of current node.
Solution:
At each node we compare the size of left subtree with the current value of k:
if head.lsize + 1 == k: current node in our answer.
if head.lsize + 1 > k: elements in left subtree are more than k, that is, the k the smallest element lies in the left subtree. So, we go left.
if head.lsize + 1 < k: the current element alongwith all the elements in the left subtree are less than the kth element we need to find. So, we go to the right subtree but also reduce k by the amount of elements in left subtree + 1(current element). By subtracting this from k we make sure that we have already taken into account the number of elements which are smaller than k and are rooted as the left subtree of current node (including the current node itself).
Code:
class Node {
int data;
Node left;
Node right;
int lsize;
public Node(int data, Node left, Node right) {
this.left = left;
this.data = data;
this.right = right;
lsize = 0;
}
}
public static void insertIntoBst(Node head, int data) {
Node newNode = new Node(data, null, null);
while (true) {
if (data > head.data) {
if (head.right == null) {
head.right = newNode;
break;
} else {
head = head.right;
}
} else {
head.lsize++; //as we go left, size of left subtree rooted
//at current node will increase, hence the increment.
if (head.left == null) {
head.left = newNode;
break;
} else {
head = head.left;
}
}
}
}
public static Node printKthElement(Node head, int k) {
if (head == null) {
return null;
}
if (head.lsize + 1 == k) return head;
else if (head.lsize + 1 > k) return printKthElement(head.left, k);
return printKthElement(head.right, k - head.lsize - 1);
}
Changes:
A new member lsize has been introduced in class Node.
Slight modification in insertIntoBst.
Major changes in printKthElement.
Corner case:
Add a check to ensure that k is between 1 and the size of the tree otherwise a null node will be returned resulting in NullPointerException.
This is working on the test cases I have tried, so far. Any suggestions or corrections are most welcome.
:)

I need to design an algorithm to return the number of nodes in a binary tree that have two children

I have come across this question to design an algorithm to count the number of nodes in a binary tree that has two children. It was mentioned that the solution should be expressed as a pair of functions(not BST member functions).
So far I could not arrive at a concrete solution and specially the part where the solution should be expressed as a pair of non BST member functions is going over my head.
//count the number of node that has got 2 children
function countNodes(nodeElement,nodeNumber){
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
//check if current node has got two childs
if(getNodeChildren(children[c])==2){
nodeNumber++;
}
//recursively check if children nodes has got 2 children
nodeNumber += countNodes(children[c],nodeNumber)
}
return nodeNumber;
}
//recursively counts the number of children that a node has got
function getNodeChildren(nodeElement){
//check if is a leaf
if(nodeElement.children == 0){
return 1;
}
else {
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
nodeNumber += getNodeChildren(children[c],nodeNumber+1);
}
return nodeNumber;
}
}
Assuming Node is a struct containing two pointers to Node, named left and right:
int count_2_ch_nodes(Node* root)
{
if (root == NULL) return 0;
// Recursively count the number of nodes that are below
// this node that have two children:
int count = 0;
if (root->left != NULL) count += count_2_ch_nodes(root->left);
if (root->right != NULL) count += count_2_ch_nodes(root->right);
// Add this node IF it has 2 children:
if (has_2_ch(root)) count++;
return count;
}
/* Returns TRUE if node has two children */
int has_2_ch(Node* node)
{
return (node->left != NULL && node->right != NULL);
}
This is the complete java code for your question.
import java.util.ArrayList;
import java.util.Scanner;
/*
* Creating datastructure for Node
* Every Node contains data given by user and leftChild and rightChild childs
* Left and rightChild childs are automatically assigned by the program
*/
class Node
{
Node leftChild, rightChild;
String data;
/*
* Assigning leftChild , rightChild and data to the node using a constructor
*/
Node(Node left, Node right, String data)
{
this.leftChild =left;
this.rightChild =right;
this.data=data;
}
}
public class FirstAnswer {
/*
* Initializing the count for number of nodes
*/
private static int count=0;
private static int numberOfNodes(Node root)
{
/*
* Writing the base case for the recursive function
* If leftChild or rightChild or both are null it returns 0 as no childs are present
*/
if ((root.leftChild ==null && root.rightChild ==null) || (root.leftChild ==null) || (root.rightChild ==null))
return 0;
else {
count+=2;
Node left=root.leftChild;
Node right=root.rightChild;
/*
* Calling the recursive function twice by making leftChild child and rightChild child of root as root
*/
System.out.println(root.data+" : "+"\n"+"Left child : "+left.data+"\n"+"Right child : "+right.data);
numberOfNodes(left);
numberOfNodes(right);
}
return count+1; //Since root node is not counted
}
public static void main(String... args)
{
Scanner sc=new Scanner(System.in);
/*
* Creating individual nodes with string data from user
* Holding them in an array list inputs
*/
ArrayList<Node> inputs=new ArrayList<>();
String status="Y";
System.out.print("Enter data for root node : ");
inputs.add(new Node(null,null,sc.next()));
while (status.equals("Y") || status.equals("y"))
{
if (inputs.size()%2==1)
{
for (int j=0;j<2;j++)
{
System.out.print("data for child "+(j+1)+" : ");
inputs.add(new Node(null,null,sc.next()));
}
/*
* Yes or No for adding more number of nodes
*/
System.out.println("Press Y or y if more inputs have to be given else press N to construct tree with given inputs...");
status=sc.next();
}
}
Node[] tree=new Node[inputs.size()];
/*
* Above is the tree which is being constructed from the nodes given by user
*/
for (int i=inputs.size()-1;i>=0;i--)
{
int j=i+1;
/*
* Making tree format by locating childs with indices at 2*p and 2*p+1
*/
if ((2*j+1)<=inputs.size())
{
tree[i]=new Node(tree[2*i+1],tree[2*i+2],inputs.get(i).data);
}
else {
tree[i]=inputs.get(i);
}
}
/*
* Calling the recursive function to count number of nodes
* Since first node is the root we start from here
*/
System.out.println(numberOfNodes(tree[0]));
}
}
Hope this helps you ;)

How do you find the nth node in a binary tree?

I want to find the nth node/element in a binary tree. Not the nth largest/smallest, just the nth in inorder order for example.
How would this be done? Is it possible to keep it to one function? Many functions employ an external variable to keep track of the iterations outside of the recursion, but that seems... lazy, for lack of a better term.
You can augment the binary search tree into an order statistic tree, which supports a "return the nth element" operation
Edit: If you just want the ith element of an inorder traversal (instead of the ith smallest element) and don't want to use external variables then you can do something like the following:
class Node {
Node left
Node right
int data
}
class IterationData {
int returnVal
int iterationCount
}
IterationData findNth(Node node, IterationData data, int n) {
if(node.left != null) {
data = findNth(node.left, data, n)
}
if(data.iterationCount < n) {
data.iterationCount++
if(data.iterationCount == n) {
data.returnVal = node.data
return data
} else if(node.right != null) {
return findNth(node.right, data, n)
} else {
return data
}
}
}
You'll need some way to return two values, one for the iteration count and one for the return value once the nth node is found; I've used a class, but if your tree contains integers then you could use an integer array with two elements instead.
In order iterative traversal, keep track of nodes passed in external variable.
public static Node inOrderInterativeGet(Node root, int which){
Stack<Node> stack = new Stack<Node>();
Node current = root;
boolean done = false;
int i = 1;
if(which <= 0){
return null;
}
while(!done){
if(current != null){
stack.push(current);
current = current.getLeft();
}
else{
if(stack.empty()){
done = true;
}
else{
current = stack.pop();
if(i == which){
return current;
}
i++;
current = current.getRight();
}
}
}
return null;
}
One way to do it is to have a size property which is left_subtree + right_subtree + 1:
class Node:
def __init__(self, data=None, left=None, right=None,
size=None):
self.data = data
self.left = left
self.right = right
self.size = size
def select(node, k):
"""Returns node with k-th position in-order traversal."""
if not node:
return None
t = node.left.size if node.left else 0
if t > k:
return select(node.left, k)
elif t < k:
return select(node.right, k - t - 1)
else:
return node
If you don't like global variable, pass to recursive function additional parameter - some int variable, let's call it auto_increment or just ai. ai stores order of current node. Also, recursive function should return maximal value of ai of current vertex subtree,because after visiting whole subtree next 'free' value will be max_ai_in_subreee+1 Something like that
int rec(int vertex,int ai){
traverseOrder[vertex] = ai
if(getChildren(vertex)!=null) return ai;
else{
for(childrens){
ai = rec(child,ai+1);
}
return ai;// subtree visited, return maximal free value upstairs.
}
}
If your function already returns some useful data, it may return some complex object which contains {useful data+ai}
Start from some vertex looks like rec(start_vertex,1);
Below is full code that you can use to find the nth element using inorder in a Binary Tree.
public class NthNodeInInoeder {
static public class Tree {
public int data;
public Tree left,right;
public Tree(int data) {
this.data = data;
}
}
static Tree root;
static int count = 0;
private static void inorder(Tree root2, int num) {
if (root2 == null)
return;
Tree node = root2;
Stack<Tree> stack = new Stack<>();
while (node != null || stack.size() > 0) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
count++;
if (count == num) {
System.out.println(node.data);
break;
}
node = node.right;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
root = new Tree(10);
root.left = new Tree(20);
root.right = new Tree(30);
root.left.left = new Tree(40);
root.left.right = new Tree(50);
int num = sc.nextInt();
inorder(root, num);
sc.close();
}
}

Check if a binary tree is balanced with iterative function?

I need to implement a non-recursive function to determine if a binary tree is balanced or not.
Anyone?
Thanks!!!
Assuming that by "balanced", you mean "height-balanced" in the AVL-tree sense, and you can store arbitrary information for each node,
For each node in post-order,
if either child doesn't exist, assume its respective height is 0.
if the height of both children differs by more than one, the tree is not balanced.
otherwise, this node's height is the larger of both children's heights.
If this point is reached, the tree is balanced.
One way to perform post-order traversal:
start at the root
loop
if this node's left child exists and does not have its height computed, visit its left child next.
else if this node's right child exists and does not have its height computed, visit its right child next.
else
compute this node's height, possibly returning early
if this node is not the root, visit its parent next.
If this point is reached, the tree is balanced.
Try this,
public class BalancedBinaryTree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public boolean isBalanced(TreeNode root) {
if (root==null) {
return true;
}
Stack<TreeNode> stack = new Stack<>();
Map<TreeNode, Integer> map = new HashMap<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
if ((node.left==null || (node.left!=null && map.containsKey(node.left))) && (node.right==null || (node.right!=null && map.containsKey(node.right)))) {
int right = (node.right==null) ? 0 : map.get(node.right);
int left = (node.left==null) ? 0 : map.get(node.left);
if (Math.abs(right-left)>1) {
return false;
} else {
map.put(node, Math.max(right, left)+1);
}
} else {
if (node.left!=null && !map.containsKey(node.left)) {
stack.push(node);
stack.push(node.left);
} else {
stack.push(node);
stack.push(node.right);
}
}
}
return true;
}
public static void main(String[] args) {
BalancedBinaryTree b = new BalancedBinaryTree();
boolean v = b.isBalanced(new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7))));
System.out.println(v);
v = b.isBalanced(new TreeNode(1, new TreeNode(2, new TreeNode(3, new TreeNode(4), new TreeNode(4)), new TreeNode(3)), new TreeNode(2)));
System.out.println(v);
v = b.isBalanced(new TreeNode(1, new TreeNode(2, new TreeNode(4, new TreeNode(8), null), new TreeNode(5)), new TreeNode(3, new TreeNode(6), null)));
System.out.println(v);
}
}
Here is a c++ code that works, inspired by the postorder traversal. The code is not commented because i do not think a simple comment is enough to explain the whole algorithm. You can execute this code manually with the example below and then you will understand everything.
bool IsBalance(const Node *head)
{
std::stack<const Node *> s;
std::stack<int> sV;
const Node *curr = head, *lastVisit = nullptr;
int deep = 0;
while (curr || !s.empty())
{
while (curr)
{
s.push(curr);
sV.push(-1);
curr = curr->m_pLeft;
}
curr = s.top();
if (sV.top() == -1)
{
sV.top() = deep;
}
if (!curr->m_pRight || curr->m_pRight == lastVisit)
{
if (!curr->m_pRight)
{
deep = 0;
}
if (std::abs(sV.top() - deep) > 1)
{
return false;
}
deep = std::max(sV.top(), deep) + 1;
lastVisit = curr;
s.pop();
sV.pop();
curr = nullptr;
}
else
{
deep = 0;
curr = curr->m_pRight;
}
}
return true;
}
examples:
(1) 21,10,3,1,#,#,5,#,6,#,#,15,12,#,#,18,16,#,#,20,#,#,35,30,22,#,#,#,40,36,#,#,42,#,45,#,#
(2) 1,2,#,4,#,5,#,#,3,6,8,#,#,#,7,#,#
(3) 3,1,#,2,#,#,#
Where nodes are arranged by PreOrder, separated by commas, and # indicates an empty node.
Find the height of left subtree and right subtree for a node of the tree, using Level order traversal and check if that node is balanced.
Repeat this for every node of the tree. For traversing all the nodes we can use level order traversal to avoid recursion.
int height(TreeNode* root){
if(!root){
return 0;
}
queue<TreeNode*> q;
q.push(root);
int count=0;
while(!q.empty()){
int size=q.size();
for(int i=0;i<size;++i){
TreeNode* temp=q.front();
q.pop();
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
count++;
}
return count;
}
bool checkEveryNode(TreeNode* root){
if(!root){
return true;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int count=q.size();
for(int i=0;i<count;++i){
TreeNode* temp=q.front();
q.pop();
int left=height(temp->left);
int right=height(temp->right);
if(abs(left-right)>1){
return false;
}
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
}
return true;
}
bool isBalanced(TreeNode* root) {
return checkEveryNode(root);
}
Time complexity of this approach is O(n^2), as we need to traverse all the descendant nodes for finding the height of a node(N) and we need to do this for all the nodes(N)

In Order Successor in Binary Search Tree

Given a node in a BST, how does one find the next higher key?
The general way depends on whether you have a parent link in your nodes or not.
If you store the parent link
Then you pick:
The leftmost child of the right child, if your current node has a right child. If the right child has no left child, the right child is your inorder successor.
Navigate up the parent ancestor nodes, and when you find a parent whose left child is the node you're currently at, the parent is the inorder successor of your original node.
If you have right child, do this approach (case 1 above):
If you don't have a right child, do this approach (case 2 above):
If you don't store the parent link
Then you need to run a complete scan of the tree, keeping track of the nodes, usually with a stack, so that you have the information necessary to basically do the same as the first method that relied on the parent link.
Python code to the Lasse's answer:
def findNext(node):
# Case 1
if node.right != None:
node = node.right:
while node.left:
node = node.left
return node
# Case 2
parent = node.parent
while parent != None:
if parent.left == node:
break
node = parent
parent = node.parent
return parent
Here's an implementation without the need for parent links or intermediate structures (like a stack). This in-order successor function is a bit different to what most might be looking for since it operates on the key as opposed to the node. Also, it will find a successor of a key even if it is not present in the tree. Not too hard to change if you needed to, however.
public class Node<T extends Comparable<T>> {
private T data;
private Node<T> left;
private Node<T> right;
public Node(T data, Node<T> left, Node<T> right) {
this.data = data;
this.left = left;
this.right = right;
}
/*
* Returns the left-most node of the current node. If there is no left child, the current node is the left-most.
*/
private Node<T> getLeftMost() {
Node<T> curr = this;
while(curr.left != null) curr = curr.left;
return curr;
}
/*
* Returns the right-most node of the current node. If there is no right child, the current node is the right-most.
*/
private Node<T> getRightMost() {
Node<T> curr = this;
while(curr.right != null) curr = curr.right;
return curr;
}
/**
* Returns the in-order successor of the specified key.
* #param key The key.
* #return
*/
public T getSuccessor(T key) {
Node<T> curr = this;
T successor = null;
while(curr != null) {
// If this.data < key, search to the right.
if(curr.data.compareTo(key) < 0 && curr.right != null) {
curr = curr.right;
}
// If this.data > key, search to the left.
else if(curr.data.compareTo(key) > 0) {
// If the right-most on the left side has bigger than the key, search left.
if(curr.left != null && curr.left.getRightMost().data.compareTo(key) > 0) {
curr = curr.left;
}
// If there's no left, or the right-most on the left branch is smaller than the key, we're at the successor.
else {
successor = curr.data;
curr = null;
}
}
// this.data == key...
else {
// so get the right-most data.
if(curr.right != null) {
successor = curr.right.getLeftMost().data;
}
// there is no successor.
else {
successor = null;
}
curr = null;
}
}
return successor;
}
public static void main(String[] args) {
Node<Integer> one, three, five, seven, two, six, four;
one = new Node<Integer>(Integer.valueOf(1), null, null);
three = new Node<Integer>(Integer.valueOf(3), null, null);
five = new Node<Integer>(Integer.valueOf(5), null, null);
seven = new Node<Integer>(Integer.valueOf(7), null, null);
two = new Node<Integer>(Integer.valueOf(2), one, three);
six = new Node<Integer>(Integer.valueOf(6), five, seven);
four = new Node<Integer>(Integer.valueOf(4), two, six);
Node<Integer> head = four;
for(int i = 0; i <= 7; i++) {
System.out.println(head.getSuccessor(i));
}
}
}
Check out here : InOrder Successor in a Binary Search Tree
In Binary Tree, Inorder successor of a
node is the next node in Inorder
traversal of the Binary Tree. Inorder
Successor is NULL for the last node in
Inoorder traversal. In Binary Search
Tree, Inorder Successor of an input
node can also be defined as the node
with the smallest key greater than the
key of input node.
With Binary Search Tree, the algorithm to find the next highest node of a given node is basically finding the lowest node of the right sub-tree of that node.
The algorithm can just be simply:
Start with the right child of the given node (make it the temporary current node)
If the current node has no left child, it is the next highest node.
If the current node has a left child, make it the current node.
Repeat 2 and 3 until we find next highest node.
we dont need parent link or stack to find the in order successor in O(log n) (assuming balanced tree).
Keep a temporary variable with the most recent value encountered in the inorder traversal that is larger than the key. if inorder traversal finds that the node does not have a right child, then this would be the inorder successor. else, the leftmost descendant of the right child.
C++ solution assuming Nodes have left, right, and parent pointers:
This illustrates the function Node* getNextNodeInOrder(Node) which returns the next key of the binary search tree in-order.
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node{
int data;
Node *parent;
Node *left, *right;
};
Node *createNode(int data){
Node *node = new Node();
node->data = data;
node->left = node->right = NULL;
return node;
}
Node* getFirstRightParent(Node *node){
if (node->parent == NULL)
return NULL;
while (node->parent != NULL && node->parent->left != node){
node = node->parent;
}
return node->parent;
}
Node* getLeftMostRightChild(Node *node){
node = node->right;
while (node->left != NULL){
node = node->left;
}
return node;
}
Node *getNextNodeInOrder(Node *node){
//if you pass in the last Node this will return NULL
if (node->right != NULL)
return getLeftMostRightChild(node);
else
return getFirstRightParent(node);
}
void inOrderPrint(Node *root)
{
if (root->left != NULL) inOrderPrint(root->left);
cout << root->data << " ";
if (root->right != NULL) inOrderPrint(root->right);
}
int main(int argc, char** argv) {
//Purpose of this program is to demonstrate the function getNextNodeInOrder
//of a binary tree in-order. Below the tree is listed with the order
//of the items in-order. 1 is the beginning, 11 is the end. If you
//pass in the node 4, getNextNode returns the node for 5, the next in the
//sequence.
//test tree:
//
// 4
// / \
// 2 11
// / \ /
// 1 3 10
// /
// 5
// \
// 6
// \
// 8
// / \
// 7 9
Node *root = createNode(4);
root->parent = NULL;
root->left = createNode(2);
root->left->parent = root;
root->right = createNode(11);
root->right->parent = root;
root->left->left = createNode(1);
root->left->left->parent = root->left;
root->right->left = createNode(10);
root->right->left->parent = root->right;
root->left->right = createNode(3);
root->left->right->parent = root->left;
root->right->left->left = createNode(5);
root->right->left->left->parent = root->right->left;
root->right->left->left->right = createNode(6);
root->right->left->left->right->parent = root->right->left->left;
root->right->left->left->right->right = createNode(8);
root->right->left->left->right->right->parent =
root->right->left->left->right;
root->right->left->left->right->right->left = createNode(7);
root->right->left->left->right->right->left->parent =
root->right->left->left->right->right;
root->right->left->left->right->right->right = createNode(9);
root->right->left->left->right->right->right->parent =
root->right->left->left->right->right;
inOrderPrint(root);
//UNIT TESTING FOLLOWS
cout << endl << "unit tests: " << endl;
if (getNextNodeInOrder(root)->data != 5)
cout << "failed01" << endl;
else
cout << "passed01" << endl;
if (getNextNodeInOrder(root->right) != NULL)
cout << "failed02" << endl;
else
cout << "passed02" << endl;
if (getNextNodeInOrder(root->right->left)->data != 11)
cout << "failed03" << endl;
else
cout << "passed03" << endl;
if (getNextNodeInOrder(root->left)->data != 3)
cout << "failed04" << endl;
else
cout << "passed04" << endl;
if (getNextNodeInOrder(root->left->left)->data != 2)
cout << "failed05" << endl;
else
cout << "passed05" << endl;
if (getNextNodeInOrder(root->left->right)->data != 4)
cout << "failed06" << endl;
else
cout << "passed06" << endl;
if (getNextNodeInOrder(root->right->left->left)->data != 6)
cout << "failed07" << endl;
else
cout << "passed07" << endl;
if (getNextNodeInOrder(root->right->left->left->right)->data != 7)
cout << "failed08 it came up with: " <<
getNextNodeInOrder(root->right->left->left->right)->data << endl;
else
cout << "passed08" << endl;
if (getNextNodeInOrder(root->right->left->left->right->right)->data != 9)
cout << "failed09 it came up with: "
<< getNextNodeInOrder(root->right->left->left->right->right)->data
<< endl;
else
cout << "passed09" << endl;
return 0;
}
Which prints:
1 2 3 4 5 6 7 8 9 10 11
unit tests:
passed01
passed02
passed03
passed04
passed05
passed06
passed07
passed08
passed09
You can read additional info here(Rus lung)
Node next(Node x)
if x.right != null
return minimum(x.right)
y = x.parent
while y != null and x == y.right
x = y
y = y.parent
return y
Node prev(Node x)
if x.left != null
return maximum(x.left)
y = x.parent
while y != null and x == y.left
x = y
y = y.parent
return y
If we perform a in order traversal then we visit the left subtree, then root node and finally the right subtree for each node in the tree.
Performing a in order traversal will give us the keys of a binary search tree in ascending order, so when we refer to retrieving the in order successor of a node belonging to a binary search tree we mean what would be the next node in the sequence from the given node.
Lets say we have a node R and we want its in order successor we would have the following cases.
[1] The root R has a right node, so all we need to do is to traverse to the left most node of R->right.
[2] The root R has no right node, in this case we traverse back up the tree following the parent links until the node R is a left child of its parent, when this occurs we have the parent node P as the in order successor.
[3] We are at the extreme right node of the tree, in this case there is no in order successor.
The implementation is based on the following node definition
class node
{
private:
node* left;
node* right;
node* parent
int data;
public:
//public interface not shown, these are just setters and getters
.......
};
//go up the tree until we have our root node a left child of its parent
node* getParent(node* root)
{
if(root->parent == NULL)
return NULL;
if(root->parent->left == root)
return root->parent;
else
return getParent(root->parent);
}
node* getLeftMostNode(node* root)
{
if(root == NULL)
return NULL;
node* left = getLeftMostNode(root->left);
if(left)
return left;
return root;
}
//return the in order successor if there is one.
//parameters - root, the node whose in order successor we are 'searching' for
node* getInOrderSucc(node* root)
{
//no tree, therefore no successor
if(root == NULL)
return NULL;
//if we have a right tree, get its left most node
if(root->right)
return getLeftMostNode(root->right);
else
//bubble up so the root node becomes the left child of its
//parent, the parent will be the inorder successor.
return getParent(root);
}
We can find the successor in O(log n) without using parent pointers (for a balanced tree).
The idea is very similar to when you have parent pointers.
We can define a recursive function that achieves this as follows:
If the current node is the target, return the left-most / smallest node of its right subtree, if it exists.
Recurse left if the target is smaller than the current node, and right if it's greater.
If the target is to the left and we haven't found a successor yet, return the current node.
Pseudo-code:
Key successor(Node current, Key target):
if current == null
return null
if target == current.key
if current.right != null
return leftMost(current.right).key
else
return specialKey
else
if target < current.key
s = successor(current.left, target)
if s == specialKey
return current.key
else
return s
else
return successor(current.right, target)
Node leftMost(Node current):
while current.left != null
current = current.left
return current
Live Java demo.
These answers all seem overly complicated to me. We really don't need parent pointers or any auxiliary data structures like a stack. All we need to do is traverse the tree from the root in-order, set a flag as soon as we find the target node, and the next node in the tree that we visit will be the in order successor node. Here is a quick and dirty routine I wrote up.
Node* FindNextInorderSuccessor(Node* root, int target, bool& done)
{
if (!root)
return NULL;
// go left
Node* result = FindNextInorderSuccessor(root->left, target, done);
if (result)
return result;
// visit
if (done)
{
// flag is set, this must be our in-order successor node
return root;
}
else
{
if (root->value == target)
{
// found target node, set flag so that we stop at next node
done = true;
}
}
// go right
return FindNextInorderSuccessor(root->right, target, done);
}
JavaScript solution
- If the given node has a right node, then return the smallest node in the right subtree
- If not, then there are 2 possibilities:
- The given node is a left child of the parent node. If so, return the parent node. Otherwise, the given node is a right child of the parent node. If so, return the right child of the parent node
function nextNode(node) {
var nextLargest = null;
if (node.right != null) {
// Return the smallest item in the right subtree
nextLargest = node.right;
while (nextLargest.left !== null) {
nextLargest = nextLargest.left;
}
return nextLargest;
} else {
// Node is the left child of the parent
if (node === node.parent.left) return node.parent;
// Node is the right child of the parent
nextLargest = node.parent;
while (nextLargest.parent !== null && nextLargest !== nextLargest.parent.left) {
nextLargest = nextLargest.parent
}
return nextLargest.parent;
}
}
Doing this in Java
TreeNode getSuccessor(TreeNode treeNode) {
if (treeNode.right != null) {
return getLeftMostChild(treeNode.right);
} else {
TreeNode p = treeNode.parent;
while (p != null && treeNode == p.right) { // traverse upwards until there is no parent (at the last node of BST and when current treeNode is still the parent's right child
treeNode = p;
p = p.parent; // traverse upwards
}
return p; // returns the parent node
}
}
TreeNode getLeftMostChild(TreeNode treeNode) {
if (treeNode.left == null) {
return treeNode;
} else {
return getLeftMostChild(treeNode.left);
}
}
We can divide this in 3 cases:
If the node is a parent: In this case we find if it has a right node and traverse to the leftmost child of the right node. In case the right node has no children then the right node is its inorder successor. If there is no right node we need to move up the tree to find the inorder successor.
If the node is a left child: In this case the parent is the inorder successor.
If the node (call it x) is a right child (of its immediate parent): We traverse up the tree until we find a node whose left subtree has x.
Extreme case: If the node is the rightmost corner node, there is no inorder successor.
Every "tutorial" that I checked on google and all answers in this thread uses the following logic: "If node doesn't have a right child then its in-order suc­ces­sor will be one of its ances­tors. Using par­ent link keep traveling up until you get the node which is the left child of its par­ent. Then this par­ent node will be the in-order successor."
This is the same as thinking "if my parent is bigger than me, then I am the left child" (property of a binary search tree). This means that you can simply walk up the parent chain until the above property is true. Which in my opinion results in a more elegant code.
I guess the reason why everyone is checking "am I the left child" by looking at branches instead of values in the code path that utilizes parent links comes from "borrowing" logic from the no-link-to-parent algorithm.
Also from the included code below we can see there is no need for stack data structure as suggested by other answers.
Following is a simple C++ function that works for both use-cases (with and without utilizing the link to parent).
Node* nextInOrder(const Node *node, bool useParentLink) const
{
if (!node)
return nullptr;
// when has a right sub-tree
if (node->right) {
// get left-most node from the right sub-tree
node = node->right;
while (node->left)
node = node->left;
return node;
}
// when does not have a right sub-tree
if (useParentLink) {
Node *parent = node->parent;
while (parent) {
if (parent->value > node->value)
return parent;
parent = parent->parent;
}
return nullptr;
} else {
Node *nextInOrder = nullptr;
// 'root' is a class member pointing to the root of the tree
Node *current = root;
while (current != node) {
if (node->value < current->value) {
nextInOrder = current;
current = current->left;
} else {
current = current->right;
}
}
return nextInOrder;
}
}
Node* previousInOrder(const Node *node, bool useParentLink) const
{
if (!node)
return nullptr;
// when has a left sub-tree
if (node->left) {
// get right-most node from the left sub-tree
node = node->left;
while (node->right)
node = node->right;
return node;
}
// when does not have a left sub-tree
if (useParentLink) {
Node *parent = node->parent;
while (parent) {
if (parent->value < node->value)
return parent;
parent = parent->parent;
}
return nullptr;
} else {
Node *prevInOrder = nullptr;
// 'root' is a class member pointing to the root of the tree
Node *current = root;
while (current != node) {
if (node->value < current->value) {
current = current->left;
} else {
prevInOrder = current;
current = current->right;
}
}
return prevInOrder;
}
}
C# implementation (Non recursive!) to find the ‘next’ node of a given node in a binary search tree where each node has a link to its parent.
public static Node WhoIsNextInOrder(Node root, Node node)
{
if (node.Right != null)
{
return GetLeftMost(node.Right);
}
else
{
Node p = new Node(null,null,-1);
Node Next = new Node(null, null, -1);
bool found = false;
p = FindParent(root, node);
while (found == false)
{
if (p.Left == node) { Next = p; return Next; }
node = p;
p = FindParent(root, node);
}
return Next;
}
}
public static Node FindParent(Node root, Node node)
{
if (root == null || node == null)
{
return null;
}
else if ( (root.Right != null && root.Right.Value == node.Value) || (root.Left != null && root.Left.Value == node.Value))
{
return root;
}
else
{
Node found = FindParent(root.Right, node);
if (found == null)
{
found = FindParent(root.Left, node);
}
return found;
}
}
public static Node GetLeftMost (Node node)
{
if (node.Left == null)
{
return node;
}
return GetLeftMost(node.Left);
}
Node successor(int data) {
return successor(root, data);
}
// look for the successor to data in the tree rooted at curr
private Node successor(Node curr, int data) {
if (curr == null) {
return null;
} else if (data < curr.data) {
Node suc = successor(curr.left, data);
// if a successor is found use it otherwise we know this node
// is the successor since the target node was in this nodes left subtree
return suc == null ? curr : suc;
} else if (data > curr.data) {
return successor(curr.right, data);
} else {
// we found the node so the successor might be the min of the right subtree
return findMin(curr.right);
}
}
private Node findMin(Node curr) {
if (curr == null) {
return null;
}
while (curr.left != null) {
curr = curr.left;
}
return curr;
}
All right I will take a shot since everyone is posting their implementations. This technique is from Introduction To Algorithms book. Basically, you need a way to backtrack to parent nodes from child nodes.
First up, you need a class to represent nodes:
public class TreeNode<V extends Comparable<V>> {
TreeNode<V> parent;
TreeNode<V> left;
TreeNode<V> right;
V data;
public TreeNode(TreeNode<V> parent, V data) {
this.parent = parent;
this.data = data;
}
public void insert(TreeNode<V> parent, V data) {
if (data.compareTo(this.data) < 0) {
if (left == null) {
left = new TreeNode<>(parent, data);
} else {
left.insert(left, data);
}
} else if (data.compareTo(this.data) > 0) {
if (right == null) {
right = new TreeNode<>(parent, data);
} else {
right.insert(right, data);
}
}
// ignore duplicates
}
#Override
public String toString() {
return data + " -> [parent: " + (parent != null ? parent.data : null) + "]";
}
}
You can have another class to run the operations:
public class BinarySearchTree<E extends Comparable<E>> {
private TreeNode<E> root;
public void insert(E data) {
if (root == null) {
root = new TreeNode<>(null, data);
} else {
root.insert(root, data);
}
}
public TreeNode<E> successor(TreeNode<E> x) {
if (x != null && x.right != null) {
return min(x.right);
}
TreeNode<E> y = x.parent;
while (y != null && x == y.right) {
x = y;
y = y.parent;
}
return y;
}
public TreeNode<E> min() {
return min(root);
}
private TreeNode<E> min(TreeNode<E> node) {
if (node.left != null) {
return min(node.left);
}
return node;
}
public TreeNode<E> predecessor(TreeNode<E> x) {
if(x != null && x.left != null) {
return max(x.left);
}
TreeNode<E> y = x.parent;
while(y != null && x == y.left) {
x = y;
y = y.parent;
}
return y;
}
public TreeNode<E> max() {
return max(root);
}
private TreeNode<E> max(TreeNode<E> node) {
if (node.right != null) {
return max(node.right);
}
return node;
}
}
The idea of finding an accessor is:
if right-subtree is not null, find the minimum value in right-subtree.
else, keep going up the tree till you get to a node that's a left child of its parent.
And for finding a predecessor, it's vice versa.
You can find a complete working example on my GitHub in this package.
In general, queries about n-th smallest (order statistic) element in a tree can be achieved in O(log n) time using an order statistic tree. One implementation is in GNU's C++ extensions: Policy-Based Data Structures. See this CodeForces blog for usage.
The way this is achieved is simply by storing an additional value at each node of a self-balancing tree that is the size of the subtree rooted at that node. Then operations Select(i) which finds the i-th smallest element and Rank(x) which finds the index such that x is the i-th smallest element can be implemented in logarithmic time complexity; see CLRS or the Wikipedia page. Then the query is simply Select(Rank(x)+1).

Resources