題目描述
給定一個二叉樹和其中的一個結點,請找出中序遍歷順序的下一個結點並且返回。注意,樹中的結點不僅包含左右子結點,同時包含指向父結點的指針。
思路(來自牛客大神回答):首先知道中序遍歷的規則是:左根右,然後作圖
結合圖,我們可發現分成兩大類:1、有右子樹的,那麼下個結點就是右子樹最左邊的點;(eg:D,B,E,A,C,G) 2、沒有右子樹的,也可以分成兩類,a)是父節點左孩子(eg:N,I,L) ,那麼父節點就是下一個節點 ; b)是父節點的右孩子(eg:H,J,K,M)找他的父節點的父節點的父節點…直到當前結點是其父節點的左孩子位置。如果沒有eg:M,那麼他就是尾節點。
看懂上面的思路代碼就很簡單了。兩天沒做題渾身難受啊。。。
python
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
# 判斷是否爲空
if not pNode:
return None
if pNode.right:
res = pNode.right
while res.left:
res = res.left
return res
while pNode.next:
tmp = pNode.next
if tmp.left == pNode:
return tmp
pNode = tmp
return None
c++
/*
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
}
};
*/
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
if(pNode == NULL) return NULL;
if(pNode->right != NULL){
TreeLinkNode* res = pNode->right;
while(res->left != NULL) res = res->left;
return res;
}
while(pNode->next != NULL){
TreeLinkNode* root = pNode->next;
if(root->left == pNode) return root;
pNode = pNode->next;
}
return NULL;
}
};