二叉树寻找中序遍历的后继节点

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;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值