求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义
题目: 求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是这两个节点间边的个数,比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2, 优化时间空间杂度。 思路一: 计算一个二叉树的最大距离有两个情况: 情况A: 路径经过左子
题目:
求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是这两个节点间边的个数,比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,
优化时间空间杂度。
思路一:
计算一个二叉树的最大距离有两个情况:
情况A: 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。
情况B: 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。
首先算出经过根节点的最大路径的距离,其实就是左右子树的深度和;然后分别算出左子树和右子树的最大距离,三者比较,最大值就是当前二叉树的最大距离了。
代码如下:
[cpp] view plaincopyprint?
- /*-----------------------------
- Copyright by yuucyf. 2011.09.02
- ------------------------------*/
- #include "stdafx.h"
- #include
- #include
- using namespace std;
- typedef struct tagSBTreeNode
- {
- tagSBTreeNode *psLeft;
- tagSBTreeNode *psRight;
- int nValue;
- int nMaxLeft;
- int nMaxRight;
- tagSBTreeNode()
- {
- psLeft = psRight = NULL;
- nValue = 0;
- nMaxLeft = nMaxRight = 0;
- }
- }S_TreeNode;
- void AddTreeNode(S_TreeNode *&psTreeNode, int nValue)
- {
- if (NULL == psTreeNode)
- {
- psTreeNode = new S_TreeNode;
- assert(NULL != psTreeNode);
- psTreeNode->nValue = nValue;
- }
- else if (psTreeNode->nValue
- {
- AddTreeNode(psTreeNode->psRight, nValue);
- }
- else
- AddTreeNode(psTreeNode->psLeft, nValue);
- }
- int MaxDepth(const S_TreeNode *psTreeNode)
- {
- int nDepth = 0;
- if (NULL != psTreeNode)
- {
- int nLeftDepth = MaxDepth(psTreeNode->psLeft);
- int nRightDepth = MaxDepth(psTreeNode->psRight);
- nDepth = (nLeftDepth > nRightDepth) ? nLeftDepth : nRightDepth;
- nDepth++;
- }
- return nDepth;
- }
- int MaxDistance(const S_TreeNode *psRootNode)
- {
- int nDistance = 0;
- if (NULL != psRootNode)
- {
- nDistance = MaxDepth(psRootNode->psLeft) + MaxDepth(psRootNode->psRight);
- int nLeftDistance = MaxDistance(psRootNode->psLeft);
- int nRightDistance= MaxDistance(psRootNode->psRight);
- nDistance = (nLeftDistance > nDistance) ? nLeftDistance : nDistance;
- nDistance = (nRightDistance > nDistance) ? nRightDistance : nDistance;
- }
- return nDistance;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- S_TreeNode *psRoot = NULL;
- AddTreeNode(psRoot, 9);
- AddTreeNode(psRoot, 6);
- AddTreeNode(psRoot, 4);
- AddTreeNode(psRoot, 8);
- AddTreeNode(psRoot, 7);
- AddTreeNode(psRoot, 15);
- AddTreeNode(psRoot, 13);
- AddTreeNode(psRoot, 16);
- AddTreeNode(psRoot, 18);
- cout "任意两个节点间的最大距离为:"
- return 0;
- }
/*----------------------------- Copyright by yuucyf. 2011.09.02 ------------------------------*/ #include "stdafx.h" #include <iostream> #include <assert.h> using namespace std; typedef struct tagSBTreeNode { tagSBTreeNode *psLeft; tagSBTreeNode *psRight; int nValue; int nMaxLeft; int nMaxRight; tagSBTreeNode() { psLeft = psRight = NULL; nValue = 0; nMaxLeft = nMaxRight = 0; } }S_TreeNode; void AddTreeNode(S_TreeNode *&psTreeNode, int nValue) { if (NULL == psTreeNode) { psTreeNode = new S_TreeNode; assert(NULL != psTreeNode); psTreeNode->nValue = nValue; } else if (psTreeNode->nValue psRight, nValue); } else AddTreeNode(psTreeNode->psLeft, nValue); } int MaxDepth(const S_TreeNode *psTreeNode) { int nDepth = 0; if (NULL != psTreeNode) { int nLeftDepth = MaxDepth(psTreeNode->psLeft); int nRightDepth = MaxDepth(psTreeNode->psRight); nDepth = (nLeftDepth > nRightDepth) ? nLeftDepth : nRightDepth; nDepth++; } return nDepth; } int MaxDistance(const S_TreeNode *psRootNode) { int nDistance = 0; if (NULL != psRootNode) { nDistance = MaxDepth(psRootNode->psLeft) + MaxDepth(psRootNode->psRight); int nLeftDistance = MaxDistance(psRootNode->psLeft); int nRightDistance= MaxDistance(psRootNode->psRight); nDistance = (nLeftDistance > nDistance) ? nLeftDistance : nDistance; nDistance = (nRightDistance > nDistance) ? nRightDistance : nDistance; } return nDistance; } int _tmain(int argc, _TCHAR* argv[]) { S_TreeNode *psRoot = NULL; AddTreeNode(psRoot, 9); AddTreeNode(psRoot, 6); AddTreeNode(psRoot, 4); AddTreeNode(psRoot, 8); AddTreeNode(psRoot, 7); AddTreeNode(psRoot, 15); AddTreeNode(psRoot, 13); AddTreeNode(psRoot, 16); AddTreeNode(psRoot, 18); cout <p><br> </p> <p> </p> <p><span>思路二:</span></p> <p>思路一不是效率最高的,因为在计算二叉树的深度的时候存在重复计算。但应该是可读性比较好的,同时也没有改变原有二叉树的结构和使用额外的全局变量。这里之间给出代码,因为代码的注释已经写的非常详细了。</p> <p> </p> <p><span>代码如下:</span></p> <p> </p> <p> </p> <p><strong>[cpp]</strong> view plaincopyprint?</p> <ol> <li><span><span>int</span><span> g_nMaxLeft = 0; </span></span></li> <li><span><span>void</span><span> MaxDistance_2(S_TreeNode *psRoot) </span></span></li> <li><span>{ </span></li> <li><span> <span>// 遍历到叶子节点,返回</span><span> </span></span></li> <li><span> <span>if</span><span> (NULL == psRoot) </span></span></li> <li><span> <span>return</span><span>; </span></span></li> <li><span> </span></li> <li><span> <span>// 如果左子树为空,那么该节点的左边最长距离为0</span><span> </span></span></li> <li><span> <span>if</span><span> (psRoot->psLeft == NULL) </span></span></li> <li><span> { </span></li> <li><span> psRoot->nMaxLeft = 0; </span></li> <li><span> } </span></li> <li><span> </span></li> <li><span> <span>// 如果右子树为空,那么该节点的右边最长距离为0</span><span> </span></span></li> <li><span> <span>if</span><span> (psRoot->psRight == NULL) </span></span></li> <li><span> { </span></li> <li><span> psRoot -> nMaxRight = 0; </span></li> <li><span> } </span></li> <li><span> </span></li> <li><span> <span>// 如果左子树不为空,递归寻找左子树最长距离</span><span> </span></span></li> <li><span> <span>if</span><span> (psRoot->psLeft != NULL) </span></span></li> <li><span> { </span></li> <li><span> MaxDistance_2(psRoot->psLeft); </span></li> <li><span> } </span></li> <li><span> </span></li> <li><span> <span>// 如果右子树不为空,递归寻找右子树最长距离</span><span> </span></span></li> <li><span> <span>if</span><span> (psRoot->psRight != NULL) </span></span></li> <li><span> { </span></li> <li><span> MaxDistance_2(psRoot->psRight); </span></li> <li><span> } </span></li> <li><span> </span></li> <li><span> <span>// 计算左子树最长节点距离</span><span> </span></span></li> <li><span> <span>if</span><span> (psRoot->psLeft != NULL) </span></span></li> <li><span> { </span></li> <li><span> <span>int</span><span> nTempMax = 0; </span></span></li> <li><span> <span>if</span><span> (psRoot->psLeft->nMaxLeft > psRoot->psLeft->nMaxRight) </span></span></li> <li><span> { </span></li> <li><span> nTempMax = psRoot->psLeft->nMaxLeft; </span></li> <li><span> } </span></li> <li><span> <span>else</span><span> </span></span></li> <li><span> { </span></li> <li><span> nTempMax = psRoot->psLeft->nMaxRight; </span></li> <li><span> } </span></li> <li><span> psRoot->nMaxLeft = nTempMax + 1; </span></li> <li><span> } </span></li> <li><span> </span></li> <li><span> <span>// 计算右子树最长节点距离</span><span> </span></span></li> <li><span> <span>if</span><span> (psRoot->psRight != NULL) </span></span></li> <li><span> { </span></li> <li><span> <span>int</span><span> nTempMax = 0; </span></span></li> <li><span> <span>if</span><span>(psRoot->psRight->nMaxLeft > psRoot->psRight->nMaxRight) </span></span></li> <li><span> { </span></li> <li><span> nTempMax = psRoot->psRight->nMaxLeft; </span></li> <li><span> } </span></li> <li><span> <span>else</span><span> </span></span></li> <li><span> { </span></li> <li><span> nTempMax = psRoot->psRight->nMaxRight; </span></li> <li><span> } </span></li> <li><span> psRoot->nMaxRight = nTempMax + 1; </span></li> <li><span> } </span></li> <li><span> </span></li> <li><span> <span>// 更新最长距离</span><span> </span></span></li> <li><span> <span>if</span><span> (psRoot->nMaxLeft + psRoot->nMaxRight > g_nMaxLeft) </span></span></li> <li><span> { </span></li> <li><span> g_nMaxLeft = psRoot->nMaxLeft + psRoot->nMaxRight; </span></li> <li><span> } </span></li> <li><span>} </span></li> </ol> <pre class="brush:php;toolbar:false">int g_nMaxLeft = 0; void MaxDistance_2(S_TreeNode *psRoot) { // 遍历到叶子节点,返回 if (NULL == psRoot) return; // 如果左子树为空,那么该节点的左边最长距离为0 if (psRoot->psLeft == NULL) { psRoot->nMaxLeft = 0; } // 如果右子树为空,那么该节点的右边最长距离为0 if (psRoot->psRight == NULL) { psRoot -> nMaxRight = 0; } // 如果左子树不为空,递归寻找左子树最长距离 if (psRoot->psLeft != NULL) { MaxDistance_2(psRoot->psLeft); } // 如果右子树不为空,递归寻找右子树最长距离 if (psRoot->psRight != NULL) { MaxDistance_2(psRoot->psRight); } // 计算左子树最长节点距离 if (psRoot->psLeft != NULL) { int nTempMax = 0; if (psRoot->psLeft->nMaxLeft > psRoot->psLeft->nMaxRight) { nTempMax = psRoot->psLeft->nMaxLeft; } else { nTempMax = psRoot->psLeft->nMaxRight; } psRoot->nMaxLeft = nTempMax + 1; } // 计算右子树最长节点距离 if (psRoot->psRight != NULL) { int nTempMax = 0; if(psRoot->psRight->nMaxLeft > psRoot->psRight->nMaxRight) { nTempMax = psRoot->psRight->nMaxLeft; } else { nTempMax = psRoot->psRight->nMaxRight; } psRoot->nMaxRight = nTempMax + 1; } // 更新最长距离 if (psRoot->nMaxLeft + psRoot->nMaxRight > g_nMaxLeft) { g_nMaxLeft = psRoot->nMaxLeft + psRoot->nMaxRight; } }

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Given a three-dimensional plane and therefore three coordinates, the task is to find the distance between the given points and display the result. On the three-dimensional plane, there are three coordinate axes, the coordinates of the x-axis are (x1, y1, z1), the coordinates of the y-axis are (x2, y2, z2), and the coordinates of the z-axis are (x3, y3, z). There is a direct formula for calculating the distance between them as follows $$\sqrt{\lgroupx2-x1\rgroup^{2}+\lgroupy2-y1\rgroup^{2}+\lgroupz2-z1\rgroup^{2 }}$$The following is an illustration showing three different coordinate axes and their coordinates. The method used below is as follows −Input coordinates (x1,

Standby is a lock screen mode that activates when the iPhone is plugged into the charger and oriented in horizontal (or landscape) orientation. It consists of three different screens, one of which is displayed full screen time. Read on to learn how to change the style of your clock. StandBy's third screen displays times and dates in various themes that you can swipe vertically. Some themes also display additional information, such as temperature or next alarm. If you hold down any clock, you can switch between different themes, including Digital, Analog, World, Solar, and Floating. Float displays the time in large bubble numbers in customizable colors, Solar has a more standard font with a sun flare design in different colors, and World displays the world by highlighting

This article is reprinted from the WeChat public account "Living in the Information Age". The author lives in the information age. To reprint this article, please contact the Living in the Information Age public account. In machine learning, a basic concept is how to judge the difference between two samples, so that the similarity and category information between the two samples can be evaluated. The measure to judge this similarity is the distance between two samples in the feature space. There are many measurement methods based on different data characteristics. Generally speaking, for two data samples x, y, define a function d(x, y). If it is defined as the distance between the two samples, then d(x, y) needs to satisfy the following basic properties : Non-negativity: d(x, y)>=0 Identity: d(x, y)=0 ⇔ x=y pair

The definition of short video refers to high-frequency pushed video content that is played on various new media platforms, suitable for viewing on the move and in a short-term leisure state, and is generally spread on new Internet media within 5 minutes. Video; the content combines skills sharing, humor, fashion trends, social hot spots, street interviews, public welfare education, advertising creativity, business customization and other themes. Short videos have the characteristics of simple production process, low production threshold, and strong participation.

The composite primary key in MySQL refers to the primary key composed of multiple fields in the table, which is used to uniquely identify each record. Unlike a single primary key, a composite primary key is formed by combining the values of multiple fields. When creating a table, you can define a composite primary key by specifying multiple fields as primary keys. In order to demonstrate the definition and function of composite primary keys, we first create a table named users, which contains three fields: id, username and email, where id is an auto-incrementing primary key and user

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

At its annual developers conference, Apple unveiled the next generation of operating systems to power its suite of devices. As usual, iOS 17 is at the center of all the major changes, with features like live voicemail, message transcription, live stickers, standby mode, full-screen live activities, interactive widgets, and more. One of the features that stands out among these new additions is Screen Distance. This is a health-centric feature focused on preventing eye strain and myopia on your iPhone screen. In this article, we will explain what screen distance is and how to enable it in iOS17. What is screen distance on iOS17? As part of the new health features introduced in iOS 17, Apple is offering a screen distance feature to help users anticipate

Want to make the front page of your school project look exciting? Nothing makes it stand out from other submissions like a nice, elegant border on the homepage of your workbook. However, the standard single-line borders in Microsoft Word have become very obvious and boring. Therefore, we show you the steps to create and use custom borders in Microsoft Word documents. How to Make Custom Borders in Microsoft Word Creating custom borders is very easy. However, you will need a boundary. Step 1 – Download Custom Borders There are tons of free borders on the internet. We have downloaded a border like this. Step 1 – Search the Internet for custom borders. Alternatively, you can go to clipping
