标签:
// 25.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; class Solution { public: TreeNode* Convert(TreeNode* pRoot) { if (pRoot == NULL) return NULL; TreeNode* ppLastNode = NULL; inOrder(pRoot, &ppLastNode); TreeNode* pRetHead = ppLastNode; while (pRetHead->left != NULL) { pRetHead = pRetHead->left; } return pRetHead; } void inOrder(TreeNode* pNode, TreeNode** ppLastNode) { if (pNode == NULL) return; if (pNode->left != NULL) { inOrder(pNode->left, ppLastNode); } // 关键代码 pNode->left = *ppLastNode; if (*ppLastNode != NULL) { (*ppLastNode)->right = pNode; } *ppLastNode = pNode; if (pNode->right != NULL) { inOrder(pNode->right, ppLastNode); } } }; int _tmain(int argc, _TCHAR* argv[]) { TreeNode root(10); TreeNode rootLeft(6); TreeNode rootRight(14); TreeNode rootLeftLeft(4); TreeNode rootLeftRight(8); TreeNode rootRightLeft(12); TreeNode rootRightRight(16); root.left = &rootLeft; root.right = &rootRight; rootLeft.left = &rootLeftLeft; rootLeft.right = &rootLeftRight; rootRight.left = &rootRightLeft; rootRight.right = &rootRightRight; Solution s; TreeNode* ret = s.Convert(&root); return 0; }根据二叉搜索树的特性,想要从小到大遍历二叉搜索树,需要实现中序遍历。如果想以实参的方式返回指针值,那么需要指向指针的指针。
void inOrder(TreeNode* pNode, TreeNode** ppLastNode) { if (pNode == NULL) return; if (pNode->left != NULL) { inOrder(pNode->left, ppLastNode); } // 关键代码 if (pNode->right != NULL) { inOrder(pNode->right, ppLastNode); } }2.在关键代码处编写特定的程序:
void inOrder(TreeNode* pNode, TreeNode** ppLastNode) { if (pNode == NULL) return; if (pNode->left != NULL) { inOrder(pNode->left, ppLastNode); } // 关键代码 pNode->left = *ppLastNode; if (*ppLastNode != NULL) { (*ppLastNode)->right = pNode; } *ppLastNode = pNode; if (pNode->right != NULL) { inOrder(pNode->right, ppLastNode); } }
标签:
原文地址:http://blog.csdn.net/chengonghao/article/details/51347266