您的位置:首页 > Web前端

(php实现剑指offer)二叉树的下一个节点

2018-03-06 22:36 316 查看
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针
思路: 考虑三种情况:
 1.是否为空树
2.节点是否根结点
3.节点是否是叶子节点<?php
/*class TreeLinkNode{
var $val;
var $left = NULL;
var $right = NULL;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
function GetNext($pNode)
{
// write code here
if($pNode==null){
return null;
}

//根结点上
if($pNode->right){
$pNode=$pNode->right;
while($pNode->left){
$pNode=$pNode->left;
}
return $pNode;

}
else if($pNode->next){
while($pNode->next!=null){
if($pNode->next->left==$pNode){
return $pNode->next;
}
$pNode=$pNode->next;
}
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: