Leetcode中几道二叉树题 II

三、平衡二叉树 (Balanced Binary Tree)

题目一:Balanced Binary Tree

Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced tree is defined as a binary tree in which the depth of the two subtree of every node never differ by more than 1.

思路:判断平衡二叉树是对树高度的判断,可以在对求树的高度算法上改造。一个树是平衡二叉树的充要条件是左右子树是平衡二叉树并且高度差不超过1.

class Solution {
public:
    vector generateTrees(int low, int high){
        vector res;
        if(low>high){
            res.push_back(NULL);   //添加叶子节点也是十分必要的呀!
            return res;
        }
        else{
            for(int i=low; i<=high; i++){
				vector left=generateTrees(low, i-1);
				vector right=generateTrees(i+1, high);
				TreeNode *root;
				for(int j=0; jleft=left[j];
						root->right=right[k];
						res.push_back(root);	
					} 
				}
			}
			return res;
        }
    }
    
    vector generateTrees(int n) {
        vector res;
        if(n==0){
            res.push_back(NULL);
            return res;
        }
        return generateTrees(1, n);
    }
};

题目二: Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

思路:求数的高度。经典算法。

class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(root==NULL) return 0;  //不一定是leaf node
        int left=maxDepth(root->left);
        int right=maxDepth(root->right);
        return 1+max(left, right);
    }
};

题目三: Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

思路:这题和上一题不一样,必须达到需要找到 leaf node 才行。

class Solution {
public:
    int minDepth(TreeNode *root) {
        if(root==NULL) return 0;
        if(root->left==NULL && root->right==NULL) return 1;  //判定为叶子节点

        int left,right;
        left=right=1<<12;
        
        if(root->left)
            left=minDepth(root->left);
        if(root->right)
            right=minDepth(root->right);
            
        return 1+min(left, right);
    }
};








你可能感兴趣的:(Leetcode)