crack the code interview 4.5
来源:互联网 发布:中控考勤软件 编辑:程序博客网 时间:2024/04/29 01:40
Write an algorithm to find the ‘next’ node (i.e., in-order successor) of a given node in a binary search tree where each node has a link to its parent.
#include <iostream>
using namespace std;struct TreeNode
{
int value;
TreeNode * left;
TreeNode * right;
TreeNode * parent;
TreeNode(int v)
{
value = v;
left = NULL;
right = NULL;
parent = NULL;
}
TreeNode(int v, TreeNode * l, TreeNode * r)
{
value = v;
left = l;
right = r;
}
};
int FindNext(TreeNode * node)
{
TreeNode * next = node;
if (node->right != NULL)
{
next = node->right;
while (next != NULL)
{
next = next->left;
}
}
else
{
if (node->parent->left == node)
{
next = node->parent;
}
else if (node->parent->right == node)
{
if (node->parent->parent != NULL)
next = node->parent->parent;
else
next = NULL;
}
}
if (next != NULL)
return next->value;
else
{
cout<<"no next"<<endl;
return 0;
}
}
int main()
{
TreeNode * node0 = new TreeNode(0);
TreeNode * node1 = new TreeNode(1);
TreeNode * node2 = new TreeNode(2, node0, node1);
node0->parent = node2;
node1->parent = node2;
TreeNode * node3 = new TreeNode(3);
TreeNode * node4 = new TreeNode(4, node2, node3);
node2->parent = node4;
node3->parent = node4;
cout<<FindNext(node1)<<endl;
return 0;
}
0 0
- crack the code interview 4.5
- crack the code interview 1.2
- crack the code interview 1.4
- crack the code interview 1.5
- crack the code interview 1.6
- crack the code interview 1.7
- crack the code interview 1.8
- crack the code interview 2.1
- crack the code interview 2.2
- crack the code interview 2.3
- crack the code interview 2.4
- crack the code interview 2.5
- crack the code interview 3.1
- crack the code interview 3.2
- crack the code interview 3.3
- crack the code interview 3.4
- crack the code interview 3.5
- crack the code interview 3.6
- 18. 微软面试题:输入一个表示整数的字符串,把该字符串转换成整数并输出
- Centos6.3下安装配置Trac和Subversion(SVN)全过程!(一)
- 【matlab编程】matlab随机数函数
- 瀑布流布局的三种实现方式
- hdu_1520_树形dp
- crack the code interview 4.5
- crack the code interview 4.6
- C++学习笔记(1)--《程序员的自我修养--链接、装载、库》笔记
- hdu 1083 Courses (简单二分匹配)
- bfs知识点
- Zedgraph用法
- 永远怀念Steve Jobs——时代的先驱者
- crack the code interview 4.7
- 驱动程序遇到问题记录