From: http://www.careercup.com/question?id=13324669
Question:
There is a tree with additional field in each node, named "next". We have to put the inorder successor in this pointer.
Answer:
public class SetInorderSuccessor
{
static Node prev=null;
void put_successor(Node node)
{
if(node==null) return;
put_successor(node.left);
if(prev!=null) prev.next=node;
prev=node;
put_successor(node.right);
}
}
使用静态变量prev来保持前驱节点很巧妙。
顺便可以解决下面的问题,
1. You are given a binary search tree of integers. Given a target integer, find the greatest integer that is smaller than the target integer.
2. A program to check if a binary tree is BST or not (from http://www.geeksforgeeks.org/archives/3042)
We can avoid the use of Auxiliary Array. While doing In-Order traversal, we can keep track of previously visited node. If the value of the currently visited node is less than the previous value, then tree is not BST.
bool isBST(struct node* root)
{
static struct node *prev = NULL;
// traverse the tree in inorder fashion and keep track of prev node
if(root)
{
if(!isBST(root->left))
return false;
// Allows only distinct valued nodes
if(prev != NULL && root->data <= prev->data)
return false;
prev = root;
return isBST(root->right);
}
return true;
}