剑指offer57_二叉树的下一个结点_题解
二叉树的下一个结点
题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
分析
方案一:最优解法
仔细观察二叉树,可以把中序下一结点归为几种类型:
- 有右子树,下一结点是右子树中的最左结点,例如:2,下一结点是 5
- 无右子树,且结点是该结点父结点的左子树,则下一结点是该结点的父结点,例如 1,下一结点是 2
- 无右子树,且结点是该结点父结点的右子树,则我们一直沿着父结点追溯,直到找到某个结点是其父结点的左子树,如果存在这样的结点,那么这个结点的父结点就是我们要找的下一结点。例如 4,下一结点是 5
代码
/*
1.时间复杂度:O(n)
2.空间复杂度:O(1)
*/
class Solution
{
public:
TreeLinkNode *GetNext(TreeLinkNode *pNode)
{
//1.有右子树,下一结点是右子树中的最左结点
if (pNode->right != NULL)
{
TreeLinkNode *pRight = pNode->right;
while (pRight->left != NULL)
{
pRight = pRight->left;
}
return pRight;
}
//2.无右子树
else
{
//结点是该结点父结点的左子树
if (pNode->next != NULL && pNode == pNode->next->left)
{
return pNode->next; //下一结点是该结点的父结点
}
//结点是该结点父结点的右子树
if (pNode->next != NULL && pNode == pNode->next->right)
{
TreeLinkNode *pNext = pNode->next;
while (pNext->next != NULL && pNext != pNext->next->left)
{
pNext = pNext->next;
}
return pNext->next;
}
}
return NULL;
}
};
方法二:暴力
算法流程:
- 根据给出的结点求出整棵树的根节点
- 根据根节点递归求出树的中序遍历,存入 \(nodes\) 中
- 在 \(nodes\) 中查找当前结点,则当前结点的下一结点即为所求
/*
1.时间复杂度:O(n)
2.空间复杂度:O(n)
*/
class Solution
{
public:
void dfs(TreeLinkNode *root, vector<TreeLinkNode *> &nodes)
{
if (!root)
{
return;
}
dfs(root->left, nodes);
nodes.emplace_back(root);
dfs(root->right, nodes);
}
TreeLinkNode *GetNext(TreeLinkNode *pNode)
{
if (!pNode)
{
return NULL;
}
TreeLinkNode *root = pNode;
while (root->next)
{
root = root->next;
}
vector<TreeLinkNode *> nodes;
dfs(root, nodes);
int n = nodes.size();
for (int i = 0; i < n; i++)
{
if (nodes[i] == pNode && i != n - 1)
{
return nodes[i + 1];
}
}
return NULL;
}
};