0.定义二叉树
class Node
{
public :
int value;
Node* left = NULL ;
Node* right = NULL ;
Node ( int v) : value ( v) { }
} ;
typedef Node* Tree;
typedef Node* pNode;
void initTree ( Tree & tree)
{
tree = new Node ( 0 ) ;
tree- > left = new Node ( 2 ) ;
tree- > right = new Node ( 3 ) ;
tree- > left- > left = new Node ( 4 ) ;
tree- > left- > right = new Node ( 10 ) ;
tree- > right- > right = new Node ( 15 ) ;
}
1.先序遍历
void printTree_1 ( Tree root)
{
stack< pNode> s;
pNode p = root;
while ( p != NULL || ! s. empty ( ) )
{
while ( p != NULL )
{
cout << p- > value << "\t" ;
s. push ( p) ;
p = p- > left;
}
if ( ! s. empty ( ) )
{
p = s. top ( ) ;
s. pop ( ) ;
p = p- > right;
}
}
}
2.中序遍历
void printTree_2 ( Tree root)
{
stack< pNode> s;
pNode p= root;
while ( p != NULL || ! s. empty ( ) )
{
while ( p != NULL )
{
s. push ( p) ;
p = p- > left;
}
if ( ! s. empty ( ) )
{
p = s. top ( ) ;
cout << p- > value << "\t" ;
p = p- > right;
s. pop ( ) ;
}
}
}
3.后序遍历
void printTree_3 ( Tree root)
{
stack< pNode> s;
pNode current = root;
pNode pre = NULL ;
s. push ( current) ;
while ( ! s. empty ( ) )
{
current = s. top ( ) ;
if ( ( current- > left == NULL && current- > right == NULL ) || ( pre != NULL && ( pre == current- > left || pre == current- > right) ) )
{
cout << current- > value << "\t" ;
s. pop ( ) ;
pre = current;
}
else
{
if ( current- > right != NULL )
s. push ( current- > right) ;
if ( current- > left != NULL )
s. push ( current- > left) ;
}
}
}
5.结果
6.根到节点的路径
bool getPathFromRoot ( pNode root, int v, vector< int > & path) {
if ( root == NULL ) {
return false ;
}
path. push_back ( root- > value) ;
if ( root- > value == v) {
return true ;
}
if ( root- > left != NULL ) {
if ( getPathFromRoot ( root- > left, v, path) == true ) {
return true ;
}
}
if ( root- > right != NULL ) {
if ( getPathFromRoot ( root- > right, v, path) == true ) {
return true ;
}
}
path. erase ( path. end ( ) - 1 ) ;
return false ;
}