剑指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);
    }
}

猜你喜欢

转载自blog.csdn.net/tkzc_csk/article/details/83575023