左神算法进阶班5_2二叉树的最远距离

【题目】

二叉树中,一个节点可以往上走和往下走,那么从节点A总能走到节点B。

节点A走到节点B的距离为:A走到B最短路径【每个节点只走一次,不能重复走】上的节点个数。

求一棵二叉树上的最远距离

即,A到B可能有多条路径,求最长路径

【题解】

使用递归,求每一个节点为头的整棵子树的最大距离,则答案在其中

可能性一:

就是左子树的最大距离

可能性二:

就是右子树的最大距离

可能性三:

从左子树到右子树的最大距离

【代码】

  

  1 #pragma once
  2 #include <iostream>
  3 #include <algorithm>
  4 #include <vector>
  5 
  6 using namespace std;
  7 
  8 struct Node
  9 {
 10     int val;
 11     Node* l;
 12     Node* r;
 13     Node(int a) :val(a), l(nullptr), r(nullptr) {}
 14 };
 15 
 16 struct returnType
 17 {
 18     int h;
 19     int maxDis;
 20     returnType(int a, int b) :h(a), maxDis(b) {}
 21 };
 22 
 23 //第一种递归
 24 returnType* findMaxDis1(Node* head)
 25 {
 26     if (head == nullptr)
 27         return new returnType(0, 0);
 28     //递归获得左右子树的大小
 29     returnType *lres, *rres;
 30     lres = findMaxDis1(head->l);
 31     rres = findMaxDis1(head->r);
 32 
 33     //判断
 34     int maxDis = max(max(lres->maxDis, rres->maxDis), lres->h + 1 + rres->h);//根据树的深度进行判断
 35     int h = max(lres->h, rres->h) + 1;//越向下深入探索,则树的深度加1
 36     return new returnType(h, maxDis);
 37 }
 38 
 39 
 40 //第二种递归
 41 vector<int> findMaxDis2(Node* head)
 42 {
 43     if (head == nullptr)
 44         return { 0, 0 };
 45 
 46     vector<int>lv, rv;
 47     lv = findMaxDis2(head->l);
 48     rv = findMaxDis2(head->r);
 49     int maxDis = max(max(lv[1], rv[1]), lv[0] + 1 + rv[0]);
 50     int h = max(lv[0], lv[0]) + 1;
 51     return { h,maxDis };
 52 }
 53 
 54 
 55 void Test()
 56 {
 57 
 58     Node* root = new Node(9);
 59     root->l = new Node(8);
 60     root->r = new Node(1);
 61     root->l->l = new Node(5);
 62     root->l->r = new Node(9);
 63     root->l->l->l = new Node(4);
 64     root->l->l->r = new Node(6);
 65     root->r->l = new Node(5);
 66     root->r->r = new Node(3);
 67     returnType* p = findMaxDis1(root);
 68     cout << p->maxDis << endl;
 69 
 70     root = nullptr;
 71     root = new Node(5);
 72     root->l = new Node(2);
 73     root->r = new Node(6);
 74     root->l->l = new Node(1);
 75     root->l->r = new Node(3);
 76     p = findMaxDis1(root);
 77     cout << p->maxDis << endl;
 78 
 79     vector<int>v;
 80     root = nullptr;
 81     root = new Node(9);
 82     root->l = new Node(8);
 83     root->r = new Node(1);
 84     root->l->l = new Node(5);
 85     root->l->r = new Node(9);
 86     root->l->l->l = new Node(4);
 87     root->l->l->r = new Node(6);
 88     root->r->l = new Node(5);
 89     root->r->r = new Node(3);
 90     v = findMaxDis2(root);
 91     cout << v[1] << endl;
 92 
 93     root = nullptr;
 94     root = new Node(5);
 95     root->l = new Node(2);
 96     root->r = new Node(6);
 97     root->l->l = new Node(1);
 98     root->l->r = new Node(3);
 99     v = findMaxDis2(root);
100     cout << v[1] << endl;
101 
102     
103 }

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11073086.html