每日一题——判断二叉树是否平衡,求一棵二叉树的镜像

来源:互联网 发布:淘宝服装推广方案 编辑:程序博客网 时间:2024/05/22 10:24

1,判断一棵二叉树是否平衡
一棵树平衡是指它根节点到叶子节点的最长路径与最短路径只差不超过1。

bool IsBanlance(Node* root,int& depth){    if(root == NULL)    {        depth = 0;        return true;    }    int leftDepth = 0;    int rightDepth = 0;    if(IsBanlance(root->left,depth) == false)        return false;    if(IsBanlance(root->right,depth) == false)        return false;    depth = (leftDepth>rightDepth)?(leftDepth+1):(rightDepth+1);    return abs(leftDepth-rightDepth)>2;}

2,求一棵树的镜像
递归,使得每个节点的左右子树互换位置即可。

//递归实现Node* mirr(Node* root){    if(root == NULL)        return NULL;    if(root->left == NULL && root->right == NULL)        return NULL;    swap(root->left,root->right);    if(root->left)        mirr(root->left);    if(root->right)        mirr(root->right);}
//非递归实现Node* mirr(Node* root){    if(root == NULL)        return NULL;    stack<Node*> sta;    Node* newroot = root;    sta.push(root);    while(stack.size())    {        Node* tmp = sta.top();        sta.pop();        if(tmp->left != NULL || tmp->right != NULL)        {            swap(tmp->left,tmp->right);        }        if(tmp->right != NULL)            sta.push(tmp->right);        if(tmp->left != NULL)            sta.push(tmp->left);    }    return newroot;}
阅读全文
0 0