PAT、蓝桥杯、LeetCode二叉树总结

复习的时候找到了以前的笔记。。感觉还记的挺详细的。。发出来方便以后查阅~

PAT

A1004 Counting Leaves (30分) [BFS, DFS, 树的层序遍历]

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 0<N<100, the number of nodes in a tree, and M (<N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] ... ID[K]

where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.

The input ends with N being 0. That case must NOT be processed.

Output Specification:

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output 0 1 in a line.

Sample Input:

2 1
01 1 02

Sample Output:

0 1

题目大意:给出一棵树,问每一层各有多少个叶子结点~

分析:可以⽤用dfs也可以⽤用bfs~如果⽤用dfs,用二维数组保存每一个有孩子结点的结点以及他们的孩子结点,从根结点开始遍历,直到遇到叶子结点,就将当前层数depth的level[depth]++;标记第depth层拥有的叶子结点数,后输出~

#include <iostream>
#include <vector>
using namespace std;
int n,m, maxDepth=-1;
vector<int> Adj[110]; //邻接表 
int level[110] = {0};//每层的叶子节点数 
void DFS(int u, int depth)
{
	if(Adj[u].size()==0){
		if(depth > maxDepth)
			maxDepth = depth;
		level[depth]++;
		return;
	}
	for(int i=0; i<Adj[u].size(); i++){
		int v = Adj[u][i];
		DFS(v, depth+1);
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	int id, k, child;
	for(int i=1; i<=m; i++){
		scanf("%d%d",&id,&k);
		for(int j=0; j<k; j++){
			scanf("%d",&child);
			Adj[id].push_back(child);
		}
	}
	DFS(1,1);
	for(int i=1; i<=maxDepth; i++){
		if(i!=1) printf(" ");
		printf("%d",level[i]);
	}
	return 0;
}
A1020 Tree Traversals (25分) [二叉树的遍历,后序中序转层序]

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2

题目大意:给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

分析:与后序中序转换为前序的代码相仿(无须构造二叉树再进行广度优先搜索~),只不过加一个变量index,表示当前根结点在二叉树中所对应的下标(从0开始),所以进行一次输出先序的递归的时候,把节点的index和value放进结构体里,再装进容vector里,这样在递归完成后,vector中按照 index排序就是层序遍历的顺序~

如果你不知道如何将后序和中序转换为先序,可参考博客:https://www.liuchuo.net/archives/2090

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N;
int post[31],in[31];
struct node{
	int index, value;
};
vector<node> ans; 
bool cmp(node a,node b){
	return a.index < b.index;
}
void pre(int root, int start, int end, int index)//index是根结点的下标 {
	if(start > end) return;
	int k=start;
	while(k<=end && in[k]!=post[root]) k++;
	ans.push_back({index, post[root]});
	pre(root-1-end+k, start, k-1, 2*index+1);
	pre(root-1, k+1, end, 2*index+2);
}
int main(){
	scanf("%d",&N);
	for(int i=0; i<N; i++){
		scanf("%d",&post[i]);
	}
	for(int i=0; i<N; i++){
		scanf("%d",&in[i]);
	}
	pre(N-1, 0, N-1, 0);
	sort(ans.begin(), ans.end(), cmp);
	for(int i=0; i<ans.size(); i++){
		if(i!=0) printf(" ");
		printf("%d",ans[i].value);
	}
	return 0;
}
A1053 Path of Equal Weight (30分) [树的遍历]

Given a non-empty tree with root R, and with weight Wi assigned to each tree node Ti. The weight of a path from R to L is defined to be the sum of the weights of all the nodes along the path from R to any leaf node L.

Now given any weighted tree, you are supposed to find all the paths with their weights equal to a given number. For example, let’s consider the tree showed in the following figure: for each node, the upper number is the node ID which is a two-digit number, and the lower number is the weight of that node. Suppose that the given number is 24, then there exists 4 different paths which have the same given weight: {10 5 2 7}, {10 4 10}, {10 3 3 6 2} and {10 3 3 6 2}, which correspond to the red edges in the figure.

img

Input Specification:

Each input file contains one test case. Each case starts with a line containing 0<N≤100, the number of nodes in a tree, M (<N), the number of non-leaf nodes, and 0<S<230, the given weight number. The next line contains N positive numbers where W**i (<1000) corresponds to the tree node T**i. Then M lines follow, each in the format:

ID K ID[1] ID[2] ... ID[K]

where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 00.

Output Specification:

For each test case, print all the paths with weight S in non-increasing order. Each path occupies a line with printed weights from the root to the leaf in order. All the numbers must be separated by a space with no extra space at the end of the line.

Note: sequence {A1,A2,⋯,An} is said to be greater than sequence {B1,B2,⋯,Bm} if there exists 1≤k<min{n,m} such that Ai=Bi for i=1,⋯,k, and Ak+1>Bk+1.

Sample Input:

20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19

Sample Output:

10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Node{
	int w;
	vector<int> child;
};
vector<Node> v;
vector<int> path;
int n,m,s;
bool cmp(int a, int b)
{
	return v[a].w > v[b].w;
}
void DFS(int index, int num, int sum)
{
	if(sum > s) return;
	if(sum == s){
		if(v[index].child.size() != 0) return;
		for(int i=0; i<num; i++)
			printf("%d%c",v[path[i]].w, i != num-1 ? ' ' : '\n');
		return;
	}
	for(int i=0 ; i<v[index].child.size(); i++){
		int node = v[index].child[i];
		path[num] = node;//存着它孩子的下标
		DFS(node, num+1, sum + v[node].w); 
	}
}
int main()
{
	scanf("%d%d%d",&n,&m,&s);
	v.resize(n), path.resize(n);
	for(int i=0; i<n; i++){
		scanf("%d",&v[i].w);
	}
	int node, child, k;
	for(int i=0; i<m; i++){
		scanf("%d%d",&node,&k);
		v[node].child.resize(k);
		for(int j=0; j<k; j++){
			scanf("%d",&v[node].child[j]);
		}
		sort(v[node].child.begin(), v[node].child.end(), cmp);
	}
	DFS(0,1,v[0].w);
	return 0;
}
A1079 Total Sales of Supply Chain (25分) [DFS, BFS, 树的遍历]

A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone involved in moving a product from supplier to customer.

Starting from one root supplier, everyone on the chain buys products from one’s supplier in a price P and sell or distribute them in a price that is r% higher than P. Only the retailers will face the customers. It is assumed that each member in the supply chain has exactly one supplier except the root supplier, and there is no supply cycle.

Now given a supply chain, you are supposed to tell the total sales from all the retailers.

Input Specification:

Each input file contains one test case. For each case, the first line contains three positive numbers: N (≤105), the total number of the members in the supply chain (and hence their ID’s are numbered from 0 to N−1, and the root supplier’s ID is 0); P, the unit price given by the root supplier; and r, the percentage rate of price increment for each distributor or retailer. Then N lines follow, each describes a distributor or retailer in the following format:

Ki ID[1] ID[2] ... ID[Ki]

where in the i-th line, Ki is the total number of distributors or retailers who receive products from supplier i, and is then followed by the ID’s of these distributors or retailers. Kj being 0 means that the j-th member is a retailer, then instead the total amount of the product will be given after Kj. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the total sales we can expect from all the retailers, accurate up to 1 decimal place. It is guaranteed that the number will not exceed 1010.

Sample Input:

10 1.80 1.00
3 2 3 5
1 9
1 4
1 7
0 7
2 6 1
1 8
0 9
0 4
0 3

Sample Output:

42.4

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
	int w;
	vector<int> child;//存放孩子结点下标 
};
vector<Node> v;
int n;
double p,r, total=0.0;
void DFS(int index, int num)
{
	if(v[index].child.size() == 0){
		total += v[index].w * pow(1+r,num);
		return;
	}
	for(int i=0; i<v[index].child.size(); i++){
		int child = v[index].child[i];
		DFS(child, num+1);
	}
}
int main()
{
	scanf("%d%lf%lf",&n,&p,&r);
	r = r/100.0;
	v.resize(n);
	int k, child;
	for(int i=0; i<n; i++){
		scanf("%d%d",&k,&child);
		if(k==0)
			v[i].w = child;//总产品数
		else{
			v[i].child.resize(k);
			v[i].child[0] = child;
			for(int j=1; j<k; j++){
				scanf("%d",&v[i].child[j]);
			}
		} 
	}
	DFS(0,0);
	printf("%.1f\n", total*p);
	return 0;
}
A1086 Tree Traversals Again (25分) [树的遍历]

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

img
Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output:

3 4 2 6 5 1

#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
using namespace std;
int n;
vector<int> pre, in, post, value;
stack<int> s;
void postorder(int root, int start, int end)
{
	if(start > end) return;
	int i=start;
	while(i<=end && pre[root]!=in[i]) i++;
	postorder(root+1, start, i-1);
	postorder(root+1+i-start, i+1, end);
	post.push_back(pre[root]);
}
int main()
{
	scanf("%d",&n);
	char str[5];
	int x, k=0;
	for(int i=0; i<n*2; i++){
		scanf("%s",str);
		if(strlen(str)==4){
			scanf("%d",&x);
			value.push_back(x);
			pre.push_back(k);
			s.push(k++);
		}else{
			in.push_back(s.top());
			s.pop();
		}
	}
	postorder(0,0,n-1);
	printf("%d",value[post[0]]);
	for(int i=1; i<n; i++){
		printf(" %d",value[post[i]]);
	}
	return 0;
}
A1090 Highest Price in Supply Chain (25分) [DFS, 树的遍历]

A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone involved in moving a product from supplier to customer.

Starting from one root supplier, everyone on the chain buys products from one’s supplier in a price P and sell or distribute them in a price that is r% higher than P. It is assumed that each member in the supply chain has exactly one supplier except the root supplier, and there is no supply cycle.

Now given a supply chain, you are supposed to tell the highest price we can expect from some retailers.

Input Specification:

Each input file contains one test case. For each case, The first line contains three positive numbers: N (≤105), the total number of the members in the supply chain (and hence they are numbered from 0 to N−1); P, the price given by the root supplier; and r, the percentage rate of price increment for each distributor or retailer. Then the next line contains N numbers, each number S**i is the index of the supplier for the i-th member. Sroot for the root supplier is defined to be −1. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the highest price we can expect from some retailers, accurate up to 2 decimal places, and the number of retailers that sell at the highest price. There must be one space between the two numbers. It is guaranteed that the price will not exceed 1010.

Sample Input:

9 1.80 1.00
1 5 4 4 -1 4 5 3 6

Sample Output:

1.85 2

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<vector<int> > v;
int n;
double p,r;
int maxDepth=-1, maxNum=0;
void dfs(int root, int depth)
{
	if(v[root].size()==0){
		if(depth > maxDepth){
			maxDepth = depth;
			maxNum = 1;
		}else if(depth == maxDepth){
			maxNum++;
		}
	}
	for(int i=0; i<v[root].size(); i++)
		dfs(v[root][i], depth+1);
}
int main()
{
	scanf("%d%lf%lf",&n,&p,&r);
	r = r/100;
	int temp,root; v.resize(n);
	for(int i=0; i<n; i++){
		scanf("%d",&temp);
		if(temp==-1)
			root = i;
		else
			v[temp].push_back(i);
	}
	dfs(root, 0);
	printf("%.2f %d\n", p*pow(1+r, maxDepth), maxNum);
	return 0;
}

蓝桥杯

蓝桥杯OJ 试题 算法训练 求先序排列(中序后序转先序)

资源限制

时间限制:1.0s 内存限制:256.0MB

问题描述
  给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。

输入格式

两行,每行一个字符串,分别表示中序和后序排列

输出格式

一个字符串,表示所求先序排列

样例输入
  BADC
  BDCA

样例输出

ABCD

#include <iostream>
#include <string>
using  namespace std;
string pre, in, post;
void trans(int inbegin, int inend, int postbegin, int postend){
    if(postbegin > postend) return;
    char ch = post[postend];
    int k=inbegin;
    while(k <= inend && in[k] != ch) k++;
    pre += ch;
    trans(inbegin, k-1, postbegin, k-1-inbegin+postbegin);
    trans(k+1, inend, postend-inend+k, postend-1);
}
int main(){
    cin >> in >> post;
    trans(0, in.size()-1, 0, post.size()-1);
    cout << pre;
    return 0;
}

LeetCode

94. Binary Tree Inorder Traversal

https://leetcode.com/problems/binary-tree-inorder-traversal/

二叉树的中序遍历,主要有三种方法:

  • Approach 1: Recursive Approach

    • 递归求中序遍历
    • 时间复杂度O(N),空间复杂度O(N)
  • Approach 2: Iterating method using Stack

    • 循环遍历
    • 需要额外空间,栈
    • 时间复杂度O(N),空间复杂度O(N)
    • while(curr) curr = curr->left; 当前结点一路push进栈;
    • 之后再pop出来,就是中序遍历顺序
    • 中序遍历首先访问左子树结点
  • Approach 3: Morris Traversal

    • 线索二叉树,不需要额外空间
    • 时间复杂度O(N),空间复杂度O(1)
  • 这一题只需要输出list,无需保留树,因此可以将root->left置为nullptr

    • 而遇到需要保留树的题,不能将root->left置为nullptr,只能用麻烦的方法,检测pre->right是否为root
    // Approach 3 的伪代码如下
    Step 1: 初始化 current = root
    Step 2: While current is not NULL
    		  If current 没有左孩子:
    			a. Print current's value
                 b. Go to the right child, i.e. current = current->right
               Else:
                 a. In current's left subtree, make current the right child of the rightmost node
                 b. Go to this left child, i.e. current = current->left
    
95. Unique Binary Search Trees II

【题意】:生成所有可能的二叉搜索树

【思路】:后序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> generateTrees(int start, int end){
        if(start > end) return {nullptr};
        vector<TreeNode*> ans;
        for(int i = start; i <= end; ++i){
            vector<TreeNode*> leftTrees = generateTrees(start, i - 1);
            vector<TreeNode*> rightTrees = generateTrees(i + 1, end);
            for(auto& left : leftTrees){
                for(auto& right : rightTrees){
                    TreeNode *cur = new TreeNode(i);
                    cur->left = left;
                    cur->right = right;
                    ans.push_back(cur);
                }
            }
        }
        return ans;
    }
    vector<TreeNode*> generateTrees(int n) {
        if(n == 0) return {};
        return generateTrees(1, n);
    }
};
96. Unique Binary Search Trees

【题意】:所有可能二叉搜索树的个数

【思路】:和上一题思路一样,当前节点 i,求左子树 i-1 的个数,右子树 n-i 的个数,两子树结果相乘。

class Solution {
public:
    int numTrees(int n) {
        vector<int> G(n + 1, 0);
        G[0] = 1;
        G[1] = 1;
        for(int i = 2; i <= n; ++i){
            for(int j = 1; j <= i; ++j){
                G[i] += G[j - 1] * G[i - j];
            }
        }
        return G[n];
    }
};
98. Validate Binary Search Tree
  • 设置MIN/MAX边界,判断每个结点是否符合条件

    • 递归
    • 迭代
  • 中序遍历

    • 递归:为什么pre设置为全局变量就OK,而设置为参数传递进来就ERROR?

      答:因为pre传入左子树(记为A区域),传入右子树(记为B区域)。当在A区域被改变时,之后再在B区域使用,B中使用的值还是最初传入的值,而不是在A区域中被修改以后的值。而设为全局变量时,在B区域中就能使用在A区域中修改之后的值了,否则,会出现错误。

      bool isValidBST(TreeNode* root) {
          TreeNode* pre = nullptr;
          return inorder(root, pre);
      }
      bool inorder(TreeNode* root, TreeNode* pre){
          if(!root) return true;
          if(!inorder(root->left, pre))
              return false;
          if(pre && pre->val >= root->val)
              return false;
           pre = root;
           return inorder(root->right, pre);
      }
      
      Wrong Answer
      Runtime: 0 ms
      Your input
      [1,1]
      Output
      true
      Expected
      false
      
    • 迭代

      Question: Binary Tree Inorder Traversal

      vector<int> inorderTraversal(TreeNode* root){
          vector<int> list;
          stack<TreeNode*> s;
          while(root || !s.empty()){
          while(root){
                  s.push(root);
                  root = root->left;
              }
              root = s.top(); s.pop();
              list.push_back(root->val);
              root = root->right;
          }
          return list;
      }
      

      Question: Kth Smallest Element in a BST

      int kthSmallest(TreeNode* root, int k){
          stack<TreeNode*> s;
          while(root || !s.empty()){
              while(root){
                  s.push(root);
                  root = root->left;
              }
              root = s.top(); s.pop();
              if(--k == 0) break;
              root = root->right;
          }
          return root->val;
      }
      

      Question: Validate Binary Search Tree

      bool isValidBST(TreeNode* root){
          if(root == nullptr) return true;
          stack<TreeNode*> s;
          TreeNode* pre = nullptr;
          while(root || !s.empty()){
              while(root){
                  s.push(root);
                  root = root->left;
              }
              root = s.top(); s.pop();
              if(pre && pre->val >= root->val)
                  return false;
              pre = root;
              root = root->right;
          }
          return true;
      }
      
100. Same Tree
  • 左右子树对应位置相等
  • 此题和下一题都是广度优先搜索(BFS)
  • BFS用队列,DFS用栈
101. Symmetric Tree
  • 左子树的右边和右子树的左边相等,左子树的左边和右子树的右边相等
  • 是镜像,不是左右子树一样
102. Binary Tree Level Order Traversal
  • 层序遍历,BFS,DFS
103. Binary Tree Zigzag Level Order Traversal
  • 此题与上一题基本一样,主要思路是修改vector的插入顺序。

  • 遇到数组输出顺序不同的题,应首先想到在数组上改变,而不是改变递归的顺序。

  • 以下代码错误

    class Solution {
    public:
      vector<vector<int>> ans;
      bool flag = false;
      vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
          dfs(root, 0);
          return ans;
      }
      void dfs(TreeNode* root, int depth){
          if(!root) return;
          if(depth == ans.size())
              ans.push_back(vector<int>());
          ans[depth].push_back(root->val);
          if(depth % 2){
              dfs(root->left, depth+1);
              dfs(root->right, depth+1);
          }else{
              dfs(root->right, depth+1);
              dfs(root->left, depth+1);
          }
      }
    };
    
  • 因为第14~20行,它右(左)子树整体搜索完,才会去搜索左(右)子树,这样右子树的右子树输出之后,才会输出左子树的左子树,(因为右子树返回之后,才会递归左子树),如下所示:

        1
      /   \
     2     3
	/		\
   4		 5
Except: [[1], [2,3], [4,5]]
Output: [[1], [2,3], [5,4]]
104. Maximum Depth of Binary Tree
  • 树的DFS本质是先序遍历,BFS本质是层序遍历

  • Question: Iteraitve method using preOrder.

    vector<int> preorder(TreeNode* root){
        stack<TreeNode*> s;
        vector<int> ans;
        while(!s.empty() || root){
            if(root){
                s.push(root);
                ans.push(root->val); // do something busy
                root = root->left;
            }else{
                root = s.top(); s.pop();
                root = root->right;
            }
        }
        return ans;
    }
    
543.Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree

          1
         / \
        2   3
       / \     
      4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

【思路】:这道题让我们求二叉树的直径,并告诉了我们直径就是两点之间的最远距离,根据题目中的例子也不难理解题意。我们再来仔细观察例子中的那两个最长路径[4,2,1,3] 和 [5,2,1,3],我们转换一种角度来看,是不是其实就是根结点1的左右两个子树的深度之和呢。那么我们只要对每一个结点求出其左右子树深度之和,这个值作为一个候选值,然后再对左右子结点分别调用求直径对递归函数,这三个值相互比较,取最大的值更新结果res,因为直径不一定会经过根结点,所以才要对左右子结点再分别算一次。为了减少重复计算,我们用哈希表建立每个结点和其深度之间的映射,这样某个结点的深度之前计算过了,就不用再次计算了,参见代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        if(!root) return 0;
        int res = getHeight(root->left) + getHeight(root->right);
        return max(res, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
    }
    int getHeight(TreeNode* root){
        if(!root) return 0;
        if(m.count(root)) return m[root];
        int h = 1 + max(getHeight(root->left), getHeight(root->right));
        return m[root] = h;
    }
private:
    unordered_map<TreeNode*, int> m;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刷子c

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值