Next node of the binary tree; binary search tree element the smaller the k

And wherein a given binary tree of a node, find the next node in a preorder traversal order and returns. Note that the node in the tree contains not only the left and right child nodes, the parent node contains a pointer pointing to.

/*
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)
	{
		TreeLinkNode* p = nullptr;
		if (pNode->right != nullptr)  //要是中序遍历的下一个结点肯定是,在右子树上
		{
			p = pNode->right;
			while (p->left)
			{
				p = p->left;
			}
			return p;
		}
		//到达这一步的话就说明,该节点的右子树为空
		//右子树为空的话,那么该结点中序遍历的下一个节点就一定在祖先节点
		//但是这个祖先节点是有要求的,就是该节点必须是祖先节点的左子树上面的结点
		p = pNode;
		while (p->next != nullptr && p->next->right == p)   //这一步执行完毕之后
		{
			p = p->next;
		}
		return p->next;  //注意返回值,是p->next
	}
};

When the right subtree given node is empty, as the case of FIG.
Here Insert Picture Description

Given a binary search tree, please find the first k smaller nodes therein. For example, (5,3,7,2,4,6,8), the numerical values ​​according to the third junction point is 4 summary.

Answer pops

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    void find(TreeNode* tree)
    {    
        if(tree == nullptr)
            return;
        find(tree->left);
        vec.push_back(tree);
        find(tree->right);
    }
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot == nullptr || k <= 0)
            return nullptr;
        find(pRoot);
        if(k > vec.size())
            return nullptr; 
        return vec[k - 1];
    }
private:
    vector<TreeNode*> vec;
    
};

There are a waste of extra space, so with the second

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    int count = 0;
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot && k > 0)
        {
            TreeNode* ret = KthNode(pRoot->left,k);
            if(ret)  //为了提高效率
                return ret;
            if(++count == k)   //切记这里是++count不是count++
                    return pRoot;
            TreeNode* ret_right = KthNode(pRoot->right,k);
            if(ret_right)  //为了提高效率
                return ret_right;
        }
        return nullptr;
    }
};
Published 230 original articles · won praise 28 · views 9301

Guess you like

Origin blog.csdn.net/weixin_43767691/article/details/103827119