1. 程式人生 > >【劍指offer系列之二叉樹】判斷是否為平衡二叉樹

【劍指offer系列之二叉樹】判斷是否為平衡二叉樹

題目:

平衡二叉樹的性質為:要麼是一顆空樹,要麼任何一個節點的左右子樹高度差的絕對值不超過1。給定一棵二叉樹的頭結點head,判斷這棵二叉樹是否為平衡二叉樹。要求時間複雜度為O(N)

思路:

採用後序遍歷。對於任何節點,先遍歷其左子樹,並用depth[ ]陣列儲存遍歷的深度,同時返回該節點是否為平衡二叉樹,如果不是,整棵樹退出遍歷,直接返回false;如果是,則遍歷右子樹。

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return isBalance(root,new
int[1]); } public boolean isBalance(TreeNode root,int []depth){ if(root==null){ depth[0]=0; return true; } boolean left=isBalance(root.left,depth); int leftdepth=depth[0]; boolean right=isBalance(root.right,depth); int rightdepth=depth[0
]; depth[0]=Math.max(leftdepth+1,rightdepth+1); if(left&&right&&Math.abs(leftdepth-rightdepth)<=1)return true; return false; } }