后序遍历

  1. 输入一棵二叉树的根节点,求该树的深度即最长路径。
  2. 输入一颗二叉树的根节点,判断是否是平衡二叉树。
  3. 求二叉树中节点的最大距离。

1、思路:

  根结点的高度等于左右子树中大者+1,也就是说先算完左右子树的高度之后再算根节点的高度,即后序遍历。

《后序遍历》
《后序遍历》
TreeDepth

 1 int TreeDepth(BinaryTreeNode* pRoot)
 2 {
 3     if(pRoot == NULL)
 4         return 0;
 5 
 6     int nLeft = TreeDepth(pRoot->m_pLeft);
 7     int nRight = TreeDepth(pRoot->m_pRight);
 8 
 9     return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
10 }

 

2、思路:

  和题1类似,先记录左右子树的高度值,再判断高度差是否在1之内。只要有一组出现大于1,就可以判断不是平衡的。

《后序遍历》
《后序遍历》
IsBalanced

 1 bool IsBalanced_Solution2(BinaryTreeNode* pRoot)
 2 {
 3     int depth = 0;
 4     return IsBalanced(pRoot, &depth);
 5 }
 6 
 7 bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth)
 8 {
 9     if(pRoot == NULL)
10     {
11         *pDepth = 0;
12         return true;
13     }
14 
15     int left, right;
16     if(IsBalanced(pRoot->m_pLeft, &left) 
17         && IsBalanced(pRoot->m_pRight, &right))
18     {
19         int diff = left - right;
20         if(diff <= 1 && diff >= -1)
21         {
22             *pDepth = 1 + (left > right ? left : right);
23             return true;
24         }
25     }
26 
27     return false;
28 }

 

3、思路:

  有两种情况:第一种是通过根节点,另一种是没有通过根节点。

《后序遍历》
《后序遍历》

 1 typedef struct _TreeNode
 2 {
 3     struct _TreeNode* pLeft; 
 4     struct _TreeNode* pRight;
 5     char cValue;
 6 }TreeNode;
 7 
 8 int MaxDisCore(TreeNode* root, int& depth)
 9 {
10     if (root == NULL) 
11     {
12         depth = 0;
13         return 0;
14     }
15     int ld, rd;
16     int maxLeft = MaxDisCore(root->pLeft, ld);
17     int maxRight = MaxDisCore(root->pRight, rd);
18     depth = ld > rd ? ld : rd + 1;
19     int maxTemp = maxLeft > maxRight ? maxLeft : maxRight;
20     return (ld + rd) > maxTemp ? (ld + rd) : maxTemp;
21 }

MaxDis

 

    原文作者:算法小白
    原文地址: https://www.cnblogs.com/wangpengjie/archive/2013/04/14/3021038.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞