[关闭]
@zsh-o 2018-10-20T14:26:37.000000Z 字数 1001 阅读 1046

非递归遍历 带有父节点的二叉树,空间复杂度为O(1)

算法


当进行回溯根节点时now = now->pParent记录旧的子节点last == now; now = now->pParent,以免重复遍历子节点,以查找其父节点

  1. #include <iostream>
  2. using namespace std;
  3. struct Node{
  4. int key;
  5. Node* pLeftChild;
  6. Node* pRightChild;
  7. Node* pParent;
  8. };
  9. int getHeight(Node* root){
  10. if(root == NULL)
  11. return 0;
  12. Node* last = root;
  13. Node* now = root;
  14. int mmax=0;
  15. int c=1;
  16. // 根节点由右孩子,但已经访问过
  17. while(now) {
  18. while(now->pLeftChild!=NULL && now->pRightChild!=last && now->pLeftChild!=last){
  19. now = now->pLeftChild;
  20. c++;
  21. }
  22. mmax = c>mmax? c:mmax;
  23. printf("%d %d\n", c, now->key);
  24. while(now!=NULL && now->pRightChild==NULL){
  25. last = now;
  26. now = now->pParent;
  27. c--;
  28. }
  29. // 根节点无右孩子
  30. if(now==NULL)
  31. break;
  32. if(last != now->pRightChild){
  33. now = now->pRightChild;
  34. c++;
  35. }else{
  36. last = now;
  37. now = now->pParent;
  38. c--;
  39. }
  40. }
  41. return mmax;
  42. }
  43. Node* initTree(){
  44. int n=0;
  45. cin>>n;
  46. if(n==0)
  47. return NULL;
  48. Node* p = new Node();
  49. p->key = n;
  50. p->pLeftChild = initTree();
  51. if(p->pLeftChild)
  52. p->pLeftChild->pParent = p;
  53. p->pRightChild = initTree();
  54. if(p->pRightChild)
  55. p->pRightChild->pParent = p;
  56. return p;
  57. }
  58. int main(){
  59. int p=0;
  60. Node* pTree = initTree();
  61. p = getHeight(pTree);
  62. cout<< p << endl;
  63. return 0;
  64. }
  65. // 1 5 22 0 0 14 0 31 0 0 9 8 98 0 0 0 7 0 0
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注