Leetcode中几道二叉树题 II

来源:互联网 发布:网线端口显示红灯 编辑:程序博客网 时间:2024/05/16 04:22

三、平衡二叉树 (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<TreeNode*> generateTrees(int low, int high){        vector<TreeNode*> res;        if(low>high){            res.push_back(NULL);   //添加叶子节点也是十分必要的呀!            return res;        }        else{            for(int i=low; i<=high; i++){vector<TreeNode*> left=generateTrees(low, i-1);vector<TreeNode*> right=generateTrees(i+1, high);TreeNode *root;for(int j=0; j<left.size(); j++){                for(int k=0; k<right.size(); k++){                    root=new TreeNode(i);root->left=left[j];root->right=right[k];res.push_back(root);} }}return res;        }    }        vector<TreeNode *> generateTrees(int n) {        vector<TreeNode*> 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);    }};








0 0
原创粉丝点击