剑指Offer: 二叉树的深度、平衡二叉树

来源:互联网 发布:北航软件工程硕士学费 编辑:程序博客网 时间:2024/04/20 17:06

二叉树的深度


输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。


/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class Solution {public:    int TreeDepth(TreeNode* pRoot)    {        if(!pRoot)  return 0;        depth=0;        getDepth(pRoot,1);//参数对应相应高度值        return depth;    }private:    void getDepth(TreeNode *root,int n){        if(root->left)   getDepth(root->left,n+1);        if(root->right)  getDepth(root->right,n+1);        if(!(root->left||root->right))    depth=max(depth,n);    }    int depth;};

平衡二叉树


输入一棵二叉树,判断该二叉树是否是平衡二叉树。


它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
求深度,求的时候要及时判断。


class Solution {public:    bool IsBalanced_Solution(TreeNode* pRoot) {        if(!pRoot)  return true;        if(getHeight(pRoot)==-1)    return false;        return true;    }private:    int getHeight(TreeNode *root){        int left{0},right{0};        if(root->left)   left=getHeight(root->left);        if(left==-1)    return -1;        if(root->right)  right=getHeight(root->right);        if(right==-1||abs(right-left)>1) return -1;        return max(left,right)+1;    }};
0 0
原创粉丝点击