【剑指offer】二叉树的下一个结点

二叉树的下一个结点

http://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e

思路:看到这种题,先画出一颗满二叉树,写出中序序列;观察某个节点的下一个节点的位置。
看出端倪后,画一个残缺的二叉树,找出规律求解即可。

讨论:

  1. 当前节点有右子树
  2. 当前节点无右子树
    2.1 当前节点是父节点的左子树
    2.2 当前节点是父节点的右子树

// 分析问题,找出归路。很考验基本功了...

class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        if (pNode == null) {
            return null;
        }

        if (pNode.right != null) { //1.当前节点有右子树
            pNode = pNode.right;
            while (pNode.left != null) {
                pNode = pNode.left;
            }
            return pNode;
        } else { // 2.当前节点无右子树
            while (pNode.next != null) {
                if (pNode.next.left == pNode) { // 2.1 当前节点是父节点的左子树
                    return pNode.next;
                } else { // 2.2 当前节点是父节点的右子树
                    pNode = pNode.next;
                }
            }
            return null;
        }
    }
}
全部评论
太牛了
点赞 回复 分享
发布于 2020-07-15 16:47

相关推荐

头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务