1. 程式人生 > >劍指offer-- 二叉樹的深度

劍指offer-- 二叉樹的深度

題目描述

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。

AC程式碼

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int TreeDepth(TreeNode root)
{ if(root == null) return 0; int leftDepth = TreeDepth(root.left); int rightDepth = TreeDepth(root.right); return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; } }

題目拓展

判斷一顆二叉樹是否為平衡二叉樹。一顆平衡二叉樹中每一個結點都滿足其左子樹與右子樹的高度差的絕對值不超過1。(一個結點的平衡因子為左子樹的高度減去右子樹的高度,平衡二叉樹滿足任意結點的平衡因子為1或-1或0)。

AC程式碼(C++)

bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth)
{    
    if(pRoot == NULL) 
    {
    	*pDepth = 0;
    	return true;
    } 
    int left, right;
    if(IsBalanced(pRoot->m_pLeft, &left) && IsBalanced(pRoot->m_pRight, &right))
    {
    	int diff = left - right;
if(diff <= 1 && diff >= -1) { *pDepth = 1 + (left > right ? left : right); return true; } } return false; } bool IsBalanced(BinaryTreeNode* pRoot) { int depth = 0; return IsBalanced(pRoot, &depth); }

AC程式碼(JAVA)

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return getDepth(root) != -1;
    }
     
    private int getDepth(TreeNode root) {
        if (root == null) return 0;
        int left = getDepth(root.left);
        if (left == -1) return -1;
        int right = getDepth(root.right);
        if (right == -1) return -1;
        return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
    }
}