zoukankan      html  css  js  c++  java
  • Balanced Binary Tree (二叉树DFS)

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    判断一棵树是否为平衡二叉树。

    思路:典型的递归,从第一个根节点开始,看左子树和右子树的深度差值是否小于等于1,然后再看由根节点的左孩子和右孩子构成的两课树是否都符合条件。

    代码:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        int maxdepth;
    public:
        void solve(TreeNode *root,int depth){
            if(root==NULL)
                return;
            if(depth>maxdepth)
                maxdepth=depth;
            solve(root->left,depth+1);
            solve(root->right,depth+1);
        }
        int getDepth(TreeNode *root) {
            maxdepth=0;
            solve(root,1);
            return maxdepth;
        }
        bool isBalanced(TreeNode *root) {
            if(root==NULL) 
                return true;
            int l,r;
            if(root->left!=NULL){
                l=getDepth(root->left);
            }else{
                l=0;
            }
            if(root->right!=NULL){
                r=getDepth(root->right);
            }else{
                r=0;
            }
            return abs(l-r)<=1&&isBalanced(root->left)&&isBalanced(root->right);
        }
    };
  • 相关阅读:
    空中楼阁 ( House )最短路
    [hdu4333]Revolving Digits
    vue element-ui el-table 选择框单选修改
    css 中间文字 两边横线
    uni-app计算scroll-view高度
    Swift Playgrounds Mac 编程学习入门
    vuecli vue.config.js 通用配置
    vuecli3 分环境打包的方案
    mysql 插入更新
    关闭进程
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4079496.html
Copyright © 2011-2022 走看看