1. 二叉树的先序、中序、后序非递归遍历
void preOrder(Node *root)
{
if(!root) return ;
stack<Node *> s;
s.push(root);
while(!s.empty())
{
Node *node = s.top();
cout<<node->val<<" ";
s.pop();
if(node->right)
s.push(node->right);
if(node->left)
s.push(node->left);
}
}
void inOrder(Node *root)
{
if(!root) return ;
stack<Node *> s;
Node *node = s.top();
while(!s.empty() || node)
{
if(node)
{
s.push(node);
node = node->left;
}else{
Node *tmp = s.top();
cout<<tmp->val<<" ";
s.pop();
node = node->right;
}
}
}
void postOrder(Node *root)
{
if(!root) return ;
stack<Node *> s; //中 右 左
s.push(root);
stack<Node *> s1; //左 右 中
while(!s.empty())
{
Node *node = s1.top();
s1.pop();
s1.push(node);
if(node->left)
s.push(node->left);
if(node->right)
s.push(node->right);
}
while(!s1.empty())
{
Node *node = s1.top();
cout<<node->val<<" ";
s1.pop();
}
}
2.在二叉树中找到一个节点的后继节点
后继:中序遍历中节点的下一个节点
前驱:中序遍历中节点的上一个节点
struct Node
{
int val;
Node *parent;
Node *left;
Node *right;
};
Node *getSuccessorNode(Node *node)
{
if(!node) return NULL;
if(node->right)
return getLeftMost(node->right);
else{
Node *pNode = node->parent;
while(!pNode && pNode->left != node) //!pNode 考虑中序最后一个节点
{
node = pNode;
pNode = node->parent;
}
return pNode;
}
}
Node *getLeftMost(Node *node)
{
if(!node) return NULL;
while(node->left)
node = node->left;
return node;
}
3.判断一棵二叉树是否是平衡二叉树
class ReturnData
{
public:
bool isB;
int height;
ReturnData(bool isB, int h)
{
this.isB = isB;
this.height = h;
}
}
bool isBalance(Node *root)
{
return process(root).isB;
}
ReturnData process(Node *node)
{
if(!node) return new ReturnData(true, 0);
ReturnData lTree = process(node->left); //判断左子树是否平衡
if(!lTree.isB)
return new ReturnData(false, 0);
ReturnData rTree = process(node->right);
if(!rTree.isB)
return new ReturnData(false, 0);
if(abs(lTree.height-rTree.height) > 1)
return new ReturnData(false, 0);
return new ReturnData(true, 1+max(lTree.height, rTree.height));
}
4. 判断一棵树是否是完全二叉树
层次遍历
- 若一个节点有右孩子,没有左孩子,返回false
- 当前遍历到的节点只有左孩子,则接下来遍历到的节点都为叶子节点
bool isComplete(Node *root)
{
if(!root) return true;
queue<Node *> q;
bool state = false; //若为true 则之后遍历到的节点都为叶子
q.push(root);
while(!q.empty())
{
Node *node = q.front();
if( (!node->left&&node->right) || (state && (node->right||node->left)) )
return false;
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
if(node->left && !node->right) //右子树为空
state = true;
}
return true;
}
5.已知一棵完全二叉树,求其节点的个数
int nodeNum(Node *root)
{
if(!root) return 0;
return help(head, 1, mostLeftLevel(head, 1));
}
int mostLeftLevel(Node *node, int h)
{
while(node && node->left)
{
node = node->left;
h++;
}
return h;
}
int help(Node *node, int level, int h) //返回第level层以node为根节点的子树个数
{
if(level == h)
return 1;
if(mostLeftLevel(node->right, level) == h) //右子树高度达到整棵树高度,则左子树为满二叉树
return (1<<(h-level)) + help(node->right, level+1, h);
else
return (1<<(h-level-1)) + help(node->left, levle=1, h);
}