110. Balanced Binary Tree

來源:互聯網
上載者:User

標籤:max   遍曆   treenode   abs   OLE   分享圖片   dep   技術   思路   

一、題目

  1、審題

  2、分析

    給出一棵二叉樹,判斷其是否是一棵二叉平衡樹。

 

二、解答

  1、思路:

    方法一、

      採用遞迴;

      每次擷取 root 結點的左子樹、右子樹的高度,比較高度差是否小於等於 1;

      同時判斷左子樹、右子樹是否也是二叉平衡樹。

public boolean isBalanced(TreeNode root) {        if(root == null)            return true;        int left = getDepthHelper(root.left);        int right = getDepthHelper(root.right);                return Math.abs(left -  right) <= 1 && isBalanced(root.left) && isBalanced(root.right);    }        private int getDepthHelper(TreeNode root) {        if(root == null)            return 0;                return Math.max(getDepthHelper(root.left), getDepthHelper(root.right)) + 1;    }

 

  方法二、

    採用深度優先遍曆的方式擷取深度,並且擷取時比較該節點的子樹是否平衡,若不平衡,返回 -1,否則返回高度。

public boolean isBalanced(TreeNode root) {        return dfsHeight(root) != -1;    }    private int dfsHeight(TreeNode root) {        if(root == null)            return 0;                int leftHeight = dfsHeight(root.left);        if(leftHeight == -1) return -1;        int rightHeight = dfsHeight(root.right);        if(rightHeight == -1) return -1;                if(Math.abs(leftHeight - rightHeight) > 1) return -1;                return Math.max(leftHeight, rightHeight) + 1;    }

 

110. Balanced Binary Tree

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.