• 二叉树的下一个节点Java实现[剑指offer]


    题目

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

    题解

    描述

    1.判断节点是否有右子树
    有就返回当前节点右子树的最左节点,注意不是最右子树的左节点
    2.若没有
    2.1判断当前节点若是左子节点
    当前节点的下一个节点是它的父节点
    2.2判断当前节点若是右子节点
    当前节点的下一个节点,需要一直向上遍历,找到它父节点的左子节点,返回父节点
    3.上述情况都不存在,则返回空

    code

    public class Solution {
        public TreeLinkNode GetNext(TreeLinkNode pNode)
        {
            //1.判断节点有右子树
            if(pNode.right!=null){
               while(pNode!=null){
                   if(pNode.left!=null){
                       pNode=pNode.left;
                   }
                   if(pNode.right!=null){
                       pNode=pNode.right;
                   }
               }
                return pNode;//该节点的下一个节点是右子树的最左节点
            }
            //2.判断节点没有右子树
            if(pNode.right==null){
                if(pNode.next!=null){
                        if(pNode.next.left!=null&&pNode.next.left==pNode){//如果该节点是左子节点,那么父节点就是他下一个节点
                        if(pNode.next!=null){
                            return pNode.next;
                        }
                    }
                    if(pNode.next.right!=null&&pNode.next.right==pNode){//如果该节点是右子节点,那么他下一个节点需要一直向上遍历,找到他父节点的左子节点
                        while(pNode.next!=null&&pNode.next.right==pNode){
                             pNode=pNode.next;
                        }
                        if(pNode.next!=null){
                            return pNode.next;
                        }
                    }
                }
            }
            return null;
        }
    }
    
  • 相关阅读:
    2011 ACM-ICPC 成都赛区解题报告(转)
    Subarray Sorting (线段树)
    sample
    gamma correction / /alpha blend
    mipmap
    antialiasing
    汇编指令
    zfighting 的问题
    勉励自己
    Ambient Occulution
  • 原文地址:https://www.cnblogs.com/ERFishing/p/11839659.html
Copyright © 2020-2023  润新知