二叉树常见算法总结(一)

一、在二叉树中,找到距离最远的两个节点的距离

《二叉树常见算法总结(一)》

在二叉树中,找到距离最远的两个节点的距离。在上面的二叉树中,最远的节点的距离是:4(路径是2-3-13-5-2)。



解决思路:遍历每个节点,找出以当前节点为根的最长路径,然后找出所有最长路径中的最大值。思路类似于最大路径和
下面直接给出代码。

void longestPathUtil(Node* root, int& left_len, int& right_len, int& max_len);  
int longestPath(Node* root)  
{  
    int left_len, right_len, max_len;  
    longestPathUtil(root, left_len, right_len, max_len);  
    return max_len;  
}  
  
void longestPathUtil(Node* root, int& left_len, int& right_len, int& max_len)  
{  
    if(root==NULL)  
    {  
        left_len = 0;  
        right_len = 0;  
        max_len = 0;  
        return;  
    }  
  
    int left_len1, right_len1, left_len2, right_len2;  
    longestPathUtil(root->left, left_len1, right_len1, max_len);  
    longestPathUtil(root->right, left_len2, right_len2, max_len);  
  
    left_len = 1+max(left_len1, right_len1);  
    right_len = 1+max(left_len2, right_len2);  
    max_len = max(left_len+right_len-1, max_len);   
}  

或者看下面的分析,转自:http://blog.csdn.net/caryaliu/article/details/8107089#

问题来源:《编程之美》3.8 求二叉树节点的最大距离

如果把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义”距离”为两个节点之间的个数。

写一个程序求一棵二叉树中相距最远的两个节点之间的距离。

如下图所示,粗箭头的边表示最长距离:

《二叉树常见算法总结(一)》

树中相距最远的两个节点是A, B

分析可知:对于二叉树,若要两个节点U,V相距最远,有两种情况:

1,从U节点到V节点之间的路径经过根节点

2,从U节点到V节点之间的路径不经过根节点,这种情况下,U,V节点必定在根节点的左子树或者右子树上,这样就转化为求以根节点的孩子节点为根节点的二叉树中最远的两个节点间的距离

上面所说的经过根节点,是指路径中包含根节点,例如:加入上图中只有左子树FGHA, 那么最长距离的两个节点是F, A,该路径中包含根节点F,也称为经过根节点。

于是我们可以递归求解,按照二叉树的中序遍历方式遍历二叉树,在遍历的过程中寻找相距最远的两个节点。

程序描述如下:

typedef struct Node {  
    struct Node *pleft;     //左孩子  
    struct Node *pright;    //右孩子  
    char chValue;           //该节点的值  
  
    int leftMaxValue;       //左子树最长距离  
    int rightMaxValue;      //右子树最长距离  
}LNode, *BinTree;  
  
void findMaxLen(BinTree root, int *maxLen) {  
    //遍历到叶子结点,返回  
    if(root == NULL)  
        return;  
  
    //如果左子树为空,那么该节点左边最长距离为0  
    if(root->pleft == NULL)  
        root->leftMaxValue = 0;  
  
    //如果右子树为空,那么该节点右边最长距离为0  
    if(root->pright == NULL)  
        root->rightMaxValue = 0;  
  
    //如果左子树不为空,递归寻找左子树最长距离  
    if(root->pleft != NULL)  
        findMaxLen(root->pleft, maxLen);  
  
    //如果右子树不为空,递归寻找右子树最长距离  
    if(root->pright != NULL)  
        findMaxLen(root->pright, maxLen);  
  
    //计算左子树中距离根节点的最长距离  
    if(root->pleft != NULL) {  
        if(root->pleft->leftMaxValue > root->pleft->rightMaxValue)  
            root->leftMaxValue = root->pleft->leftMaxValue + 1;  
        else  
            root->leftMaxValue = root->pleft->rightMaxValue + 1;  
    }  
  
    //计算右子树中距离根节点的最长距离  
    if(root->pright != NULL) {  
        if(root->pright->leftMaxValue > root->pright->rightMaxValue)  
            root->rightMaxValue = root->pright->leftMaxValue + 1;  
        else  
            root->rightMaxValue = root->pright->rightMaxValue + 1;  
    }  
  
    //更新最长距离  
    if(root->leftMaxValue + root->rightMaxValue > *maxLen)  
        *maxLen = root->leftMaxValue + root->rightMaxValue;  
}  

二、求二叉树的深度和宽度
二叉树的深度:二叉树的根结点所在的层数为1,根结点的孩子结点所在的层数为2,以此下去。深度是指所有结点中最深的结点所在的层数。

        二叉树的宽度:所有深度中含有的最多的子叶数

//求二叉树的深度  
int GetDepth(tagBiNode *pRoot)  
{  
    if (pRoot == NULL)  
    {  
        return 0;  
    }  
  
    //  int nLeftLength = GetDepth(pRoot->m_left);  
    //  int nRigthLength = GetDepth(pRoot->m_right);  
    //  return nLeftLength > nRigthLength ? (nLeftLength + 1) : (nRigthLength + 1);  
  
    return GetDepth(pRoot->left) > GetDepth(pRoot->right) ?   
        (GetDepth(pRoot->left) + 1) : (GetDepth(pRoot->right) + 1);  
}  
  
//求二叉树的宽度  
int GetWidth(tagBiNode *pRoot)  
{  
    if (pRoot == NULL)  
    {  
        return 0;  
    }  
  
    int nLastLevelWidth = 0;//记录上一层的宽度  
    int nTempLastLevelWidth = 0;  
    int nCurLevelWidth = 0;//记录当前层的宽度  
    int nWidth = 1;//二叉树的宽度  
    queue<BiNode *> myQueue;  
    myQueue.push(pRoot);//将根节点入队列  
    nLastLevelWidth = 1;      
    tagBiNode *pCur = NULL;  
  
    while (!myQueue.empty())//队列不空  
    {  
        nTempLastLevelWidth = nLastLevelWidth;  
        while (nTempLastLevelWidth != 0)  
        {  
            pCur = myQueue.front();//取出队列头元素  
            myQueue.pop();//将队列头元素出对  
  
            if (pCur->left != NULL)  
            {  
                myQueue.push(pCur->left);  
            }  
  
            if (pCur->right != NULL)  
            {  
                myQueue.push(pCur->right);  
            }  
  
            nTempLastLevelWidth--;  
        }  
  
        nCurLevelWidth = myQueue.size();  
        nWidth = nCurLevelWidth > nWidth ? nCurLevelWidth : nWidth;  
        nLastLevelWidth = nCurLevelWidth;  
    }  
  
    return nWidth;  
}  

三、二叉树系列 – 二叉树的深度,例 [LeetCode]

二叉树的深度的概念最值得注意的地方,在于 到”叶子”节点的距离。

一般来说,如果直接说“深度”,都是指最大深度,即最远叶子的距离。

1. 二叉树的最小深度

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

// Definition for binary tree
 struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

 class Solution {
 public:
     int minDepth(TreeNode *root) {
     }
 };

因为深度是必须到叶子节点的距离,因此使用深度遍历时,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。

因此,当发现当前处理的节点有单个孩子是空时,返回一个极大值INT_MAX,防止其干扰结果。

 class Solution {
 public:
     int minDepth(TreeNode *root) {
         if(!root) return 0;
         if(!root -> left && !root -> right) return 1;   //Leaf means should return depth.
         int leftDepth = 1 + minDepth(root -> left);
         leftDepth = (leftDepth == 1 ? INT_MAX : leftDepth);
         int rightDepth = 1 + minDepth(root -> right);
         rightDepth = (rightDepth == 1 ? INT_MAX : rightDepth);  //If only one child returns 1, means this is not leaf, it does not return depth.
        return min(leftDepth, rightDepth);
    }
};

当然,这道题也能用层次遍历来做。

class Solution {
struct LevNode{
    TreeNode* Node;
    int Lev;
};
public:
    int minDepth(TreeNode *root) {
        if(NULL == root) return 0;
        queue<LevNode> q;
        LevNode lnode;
        lnode.Node = root;
        lnode.Lev = 1;
        q.push(lnode);
        while(!q.empty()){
            LevNode curNode = q.front();
            q.pop();
            if(NULL == (curNode.Node) -> left && NULL == (curNode.Node) -> right)
                return (curNode.Lev);
            if(NULL != (curNode.Node) -> left){
                LevNode newNode;
                newNode.Node = (curNode.Node) -> left;
                newNode.Lev = (curNode.Lev + 1);
                q.push(newNode);
            }
            if(NULL != (curNode.Node) -> right){
                LevNode newNode;
                newNode.Node = (curNode.Node) -> right;
                newNode.Lev = (curNode.Lev + 1);
                q.push(newNode);
            }
        }
        return 0;
    }
};

对于这道题,LeetCode 两种解法的时间都是 48ms 

2. 二叉树的最大深度

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

最大深度也是到叶子节点的长度,但是因为是求最大深度,单个孩子为空的非叶子节点不会干扰到结果,因此用最简洁的处理方式就可以搞定。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(!root) return 0;
        int leftDepth = maxDepth(root -> left) + 1;
        int rightDepth = maxDepth(root -> right) + 1;
        return max(leftDepth, rightDepth);
    }
};

    原文作者:Citronnelle2
    原文地址: https://blog.csdn.net/zhouwei1221q/article/details/48107211
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞