题目:在二叉树中找到一个节点中序遍历的下一个节点
1、有父指针。分两种情况
Node* FindNextNode(Node* node)
{
if (_root == NULL || node == NULL)
return NULL;
Node* next = NULL;
//1、右不为空,找到右子树的最左节点即为下一个节点
if (node->_right != NULL)
{
Node* right = node->_right;
while (right->_left)
right = right->_left;
next = right;
}
//2、右子树为空,顺着父指针往上找,直到找到一个节点是其父节点的左孩子,则这个父节点就是下一个节点
else
{
Node* parent = node->_parent;
Node* cur = node;
//如果parent不为空并且当前节点是parent的右孩子,则一直往上找
while (parent && cur == parent->_right)
{
cur = parent;
parent = parent->_parent;
}
next = parent;
}
return next;
}
2、普通二叉树,借助中序遍历
//查找中序遍历的某个节点的下一个节点
Node* FindNextNode(Node* node)
{
if (_root == NULL || node == NULL)
return NULL;
bool find = false;
stack<Node*> s;
Node* cur = _root;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->_LeftChild;
}
Node* top = s.top();
s.pop();
if (find)
return top;
if (top == node)
find = true;
cur = top->_RightChild;
}
if (s.empty())
cout << "最后一个节点" << endl;
return NULL;
}
题目:判断一棵二叉树是否平衡(左子树和右子树的高度不超过1)
bool Isbalance()
{
int depth = 0;
return _Isbalance(_root,depth);
}
//用后序遍历的方式遍历整课二叉树,在遍历到某一节点之后根据它左右节点的深度
//判断当前节点是否平衡,再计算当前节点的深度。知道遍历到根节点
bool _Isbalance(Node*& root, int& depth)
{
if (root == NULL)
{
depth = 0;
return true;
}
int left = 0;
int right = 0;
if (_Isbalance(root->_left, left) && _Isbalance(root->_right, right))
{
if (abs(left - right) <= 1)
{
depth = (left > right ? left + 1 : right + 1);
return true;
}
}
return false;
}