20190518-剑指offer8-AcWing-19. 二叉树的下一个节点

剑指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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值