《剑指offer》第39题:平衡二叉树

来源:互联网 发布:编程原本 pdf 下载 编辑:程序博客网 时间:2024/05/21 09:45

代码:

class Solution {public:    bool IsBalanced(TreeNode* pRoot, int* pDepth)    {        if (pRoot == NULL)        {            *pDepth = 0;            return true;        }        int nLeft ;        int nRight ;        if (IsBalanced(pRoot->left, &nLeft) && IsBalanced(pRoot->right, &nRight))        {            int dif = nLeft - nRight;            if (abs(dif)<2)            {                  *pDepth = 1 + ((nLeft > nRight) ? nLeft : nRight);                return true;            }        }        return false;    }    bool IsBalanced_Solution(TreeNode* pRoot) {        int pDepth = 0;        return IsBalanced(pRoot, &pDepth);    }};

曾经在这段代码中出现的错误:

*pDepth = 1 + ((nLeft > nRight) ? nLeft : nRight);

这一行里,+? : 优先级高,因此需要用括号显示确定优先级。

0 0