題目:給定一個(gè)二叉樹(shù)和其中的一個(gè)結(jié)點(diǎn),請(qǐng)找出中序遍歷順序的下一個(gè)結(jié)點(diǎn)并且返回呜笑。注意火脉,樹(shù)中的結(jié)點(diǎn)不僅包含左右子結(jié)點(diǎn)牵寺,同時(shí)包含指向父結(jié)點(diǎn)的指針。
練習(xí)地址
https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e
參考答案
/*
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) {
for (; pNode.next != null && pNode.next.right == pNode; pNode = pNode.next);
return pNode.next;
}
for (pNode = pNode.right; pNode.left != null; pNode = pNode.left);
return pNode;
}
}
復(fù)雜度分析
- 時(shí)間復(fù)雜度:O(n)妒蛇。
- 空間復(fù)雜度:O(1)机断。