【树】二叉树的深度 + 树的最小深度 + 判断是否为平衡二叉树

求树的深度(根到叶子节点)

很简单..代码:

int TreeDepth(TreeNode* pRoot) {
    if(pRoot == NULL)
        return 0;
    if(pRoot->left == NULL && pRoot->right == NULL)
        return 1;
    
    return std::max( TreeDepth(pRoot->left), TreeDepth(pRoot->right)) + 1;
}


求树的最小深度。

代码:

int MinDepth(Treenode* root) {
	if(root == NULL)
		return 0;
	if(root->left == NULL)
		return 1 + MinDepth(root->right);
	if(root->right == NULL)
		return 1 + MinDepth(root->left);
	
	return 1 + std::min(MinDepth(root->left), MinDepth(root->right));
}


输入一棵二叉树,判断该二叉树是否是平衡二叉树。

代码:(后序遍历的思想:先得出左右孩子的深度了 才遍历到根)

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot, int& depth) {
        if(pRoot == NULL){
            depth = 0;
            return true;
        }

        int leftDepth = 0;
        int rightDepth = 0;
        if (IsBalanced_Solution(pRoot->left, leftDepth) &&
           IsBalanced_Solution(pRoot->right, rightDepth) ) {
            int diff = leftDepth - rightDepth;
            if(diff >= -1 && diff <= 1){
            	depth = 1 + std::max(leftDepth, rightDepth);
                return true;
            }
        }
        return false;
    }
    
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth = 0;
        return IsBalanced_Solution(pRoot, depth);
    }
};

你可能感兴趣的:(数据结构&算法,【笔面试准备】,【树】)