题目
给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。
注意:
- 如果给定的节点是中序遍历序列的最后一个,则返回空节点;
- 二叉树一定不为空,且给定的节点一定不是空节点; 数据范围 树中节点数量 [0,100][0,100]。
样例 假定二叉树是:[2, 1, 3, null, null, null, null], 给出的是值等于2的节点。
则应返回值等于3的节点。
解释:该二叉树的结构如下,2的后继节点是3。
2
/ \
1 3
解析
- 若该节点有右儿子,则右儿子最左边的节点就是当前节点的后继;
- 若该节点无右儿子,则需要沿着父节点向上找。找到第一个是其父节点左儿子的节点,该节点的父节点是当前节点的后继。
代码
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->right) {
p = p->right;
while(p->left) p = p->left;
return p;
}
while (p->father && p == p->father->right) p = p->father;
return p->father;
}
};
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 q.right:
q = q.right
while q.left:
q = q.left
return q
while q.father and q == q.father.right:
q = q.father
return q.father
GO
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* Father *TreeNode
* }
*/
func inorderSuccessor(p *TreeNode) *TreeNode {
if p.Right != nil {
p = p.Right
for p.Left != nil {
p = p.Left
}
return p
}
for p.Father != nil && p == p.Father.Right {
p = p.Father
}
return p.Father
}