The next node of the Binary Tree "Sword refers to offer" and the Binary Tree "Sword refers to offer"
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e? Rp = 3 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Given a binary tree and one of the nodes, find the next node in the middle order traversal order and return it. Note that the node in the tree contains not only the left and right child nodes, but also the pointer to the parent node.
Ideas
We draw a binary tree to observe the features. It is obvious that the next node that meets the characteristics of the question meets the following conditions.
1. If a node has a right subtree, the next node is the leftmost node in the right subtree.
2. If a node does not have a right subtree and the node is the left subtree of the parent node, the next node is the parent node.
3. if a node has neither the right subtree nor the right subtree of the parent node, We need to traverse the parent node layer by layer, until a new node is the left child of its parent node, the parent node of the new node is the node we requested.
using namespace std;/*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==nullptr)return nullptr;if(pNode->right!=nullptr){TreeLinkNode *pRight = pNode->right;while(pRight->left!=nullptr)pRight = pRight->left;return pRight;}else if(pNode->next!=nullptr){TreeLinkNode *pCurNode = pNode;TreeLinkNode *pParent = pNode->next;while(pParent!=nullptr && pCurNode == pParent->right){pCurNode = pParent;pParent = pParent->next;}return pParent;}}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source