标签:过程 weight font pre val bsp ace amp treenode
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 class Solution { 12 public: 13 //实现中序遍历,对于二叉搜索树中序遍历是按节点从小到大排序 14 TreeNode *KthNodeCore(TreeNode *root, int &k)//注意此处k为引用,因为在操作过程中k改变 15 { 16 TreeNode *target = NULL; 17 if(root->left != NULL) 18 { 19 target = KthNodeCore(root->left,k); 20 } 21 if(target == NULL)//无左节点且还未找到,返回其叶子节点的父节点,k-- 22 { 23 if(k == 1) 24 target = root; 25 k--; 26 } 27 if(target == NULL && root->right != NULL)//找右结点 28 { 29 target = KthNodeCore(root->right,k); 30 } 31 return target; 32 } 33 TreeNode* KthNode(TreeNode* pRoot, int k) 34 { 35 if(pRoot == NULL || k == 0) 36 return NULL; 37 return KthNodeCore(pRoot,k); 38 } 39 };
标签:过程 weight font pre val bsp ace amp treenode
原文地址:http://www.cnblogs.com/qqky/p/7123227.html