首页 > 学院 > 开发设计 > 正文

二叉树的下一个结点

2019-11-08 03:22:03
字体:
来源:转载
供稿:网友
题目描述

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

IDEA

中序遍历:左根右

1)如果该节点有右孩子:则该节点的下一个节点是其右孩子的左孩子;

2)若果该节点没有右孩子:

a.如果该节点的其父节点的左孩子,则其下一个节点是其父节点

b.如果该节点的其父节点的右孩子,找他的父节点的父节点的父节点...直到当前结点是其父节点的左孩子位置。

CODE

/*public 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){            pNode=pNode.right;            while(pNode.left!=null){                pNode=pNode.left;            }            return pNode;        }        while(pNode.next!=null){            if(pNode.next.left==pNode)                return pNode.next;            pNode=pNode.next;        }        return null;    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表