剑指offer8-AcWing-19. 二叉树的下一个节点
给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点
注意:
如果给定的节点是中序遍历序列的最后一个,则返回空节点;
二叉树一定不为空,且给定的节点一定不是空节点;
样例
假定二叉树是:[2, 1, 3, null, null, null, null], 给出的是值等于2的节点。
则应返回值等于3的节点。
解释:该二叉树的结构如下,2的后继节点是3。
2
/ \
1 3
思路:
多种情况考虑:
1.若p结点为空,则下一个结点可以直接返回空即可
2.若是p结点有右节点,则返回其右节点的最左子结点
3.若是p结点没有右子树,则网上遍历其父结点,并判断,该结点是否否父节点的右子树,若是父节点的右子树,则继续网上遍历。直到该节点是父节点的左子树结点, 直接返回其父节点即可。
C++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode *father;
* TreeNode(int x) : val(x), left(NULL), right(NULL), father(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* p) {
if(p == NULL){
return NULL;
}
TreeNode* pnext = NULL;
if(p->right != NULL){
pnext = p->right;
while(pnext->left != NULL){
pnext = pnext->left;
}
}else if(p->father != NULL){
pnext = p->father;
while(pnext != NULL && pnext->right == p){
p = pnext;
pnext = pnext->father;
}
}
return pnext;
}
};
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.father = None
class Solution(object):
def inorderSuccessor(self, q):
"""
:type q: TreeNode
:rtype: TreeNode
"""
if not q:
return None
qnext = None
if q.right:
qnext = q.right
while qnext.left:
qnext = qnext.left
elif q.father:
qnext = q.father
while qnext and qnext.right == q:
q = qnext
qnext = qnext.father
return qnext