zoukankan      html  css  js  c++  java
  • 剑指Offer(书):二叉树的下一个节点

    题目:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

    分析:若一个节点有右子树,那么他的下一个节点就是他右子树中的最左子节点。若没有右子树,且没有父节点,那么他的下一个节点为空。若没有右子树,且节点是父节点的左节点,那么父节点就是他的下一个节点。若没有右子树且节点不是父节点的左节点,那么沿着父节点一直向上遍历,直到其节点值的右子树不为他自己。

    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        if (pNode == null) {
            return null;
        }
        if (pNode.right == null) {
            if (pNode.next == null) {
                return null;
            }
            while (pNode.next.right == pNode) {
                pNode = pNode.next;
                if (pNode.next == null) {
                    return null;
                }
            }
            return pNode.next;
        }
        pNode = pNode.right;
        while (pNode.left != null) {
            pNode = pNode.left;
        }
        return pNode;
    }
  • 相关阅读:
    第 7 章 Neutron
    第 7 章 Neutron
    第 7 章 Neutron
    第 7 章 Neutron
    第 7 章 Neutron
    第 7 章 Neutron
    第 7 章 Neutron
    第 7 章 Neutron
    第 7 章 Neutron
    iOS 屏幕旋转 nav+tabbar+present(网页) 2016
  • 原文地址:https://www.cnblogs.com/liter7/p/9426011.html
Copyright © 2011-2022 走看看