温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetcode后继者怎么实现

发布时间:2021-12-15 12:02:56 来源:亿速云 阅读:118 作者:iii 栏目:大数据

本篇内容主要讲解“leetcode后继者怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“leetcode后继者怎么实现”吧!

设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。

如果指定节点没有对应的“下一个”节点,则返回null。

示例 1:

输入: root = [2,1,3], p = 1

  2

 / \

1   3

输出: 2

示例 2:

输入: root = [5,3,6,2,4,null,null,1], p = 6

      5

     / \

    3   6

   / \

  2   4

 /   

1

输出: null

解题思路:

1,类似二叉搜索树的查找,区别是查找当前值的下一个节点

2,如果p.Value>=root.Value,后继节点一定在右子树

3,如果p.Value<root.Value,后继节点要么是左子树,要么是root自己

A,当在左子树没有找到,说明是root自己

B,找到了就在左子树中

代码实现

递归实现

/** * Definition for a binary tree node. * type TreeNode struct { *     Val int *     Left *TreeNode *     Right *TreeNode * } */func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {   if root==nil || p==nil{       return nil   }
  if root.Val<=p.Val{       return inorderSuccessor(root.Right,p)   }        p0:=inorderSuccessor(root.Left,p)     if p0!=nil{       return p0     }     return root}

非递归实现

func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {   if root==nil || p==nil{       return nil   }   var q []*TreeNode   var r []*TreeNode   for len(q)>0 || root!=nil{       for root!=nil && root.Left!=nil{           q=append(q,root)           root=root.Left       }       fmt.Println(len(q),root,root==nil)       if root==nil{            l:=len(q)            if l>0{                root=q[l-1]                q=q[:l-1:l-1]                 //fmt.Println(len(q),root,root==nil)                   r=append(r,root)                    root=root.Right
           }       }else{       r=append(r,root)        //fmt.Println(len(q),root,root.Right)        root=root.Right      }   }   for i:=0;i<len(r)-1;i++{       if r[i]==p{           return r[i+1]       }   }   return nil}

到此,相信大家对“leetcode后继者怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI