标签:io 数据 for ar 代码 ef leetcode on
原题:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.
思路:递归判断左右子树是否为BST。代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode *root) { if (root==NULL) return true; if (treeDepth(root->left)==-1||treeDepth(root->right)==-1) return false; return abs(treeDepth(root->left)-treeDepth(root->right))<=1; } int treeDepth(TreeNode *root){ if (root==NULL) return 0; if (treeDepth(root->left)==-1 || treeDepth(root->right)==-1 || abs(treeDepth(root->left)-treeDepth(root->right))>1) return -1; return max(treeDepth(root->left),treeDepth(root->right))+1; } };超大规模数据集的情况下超时- -#。
这个程序的缺点在于,它需要把整颗树都遍历一遍之后才能给出答案,而其实在扫描过程中一旦遇到左右子树不相同的情况时我们就已经可以结束程序了。像这种递归怎么办比较好呢?参考了网上别人的代码后发现他们多用了一个全局变量。每次多检查一次balanced的值,如果为false直接跳出递归!
class Solution { public: bool balanced = true; bool isBalanced(TreeNode *root) { treeDepth(root); return balanced; } int treeDepth(TreeNode *root){ if(!balanced) return -1; if (root==NULL) return 0; if ( abs(treeDepth(root->left)-treeDepth(root->right))>1 ) balanced = false; return max(treeDepth(root->left),treeDepth(root->right))+1; } };AC
【Leetcode长征系列】Balanced Binary Tree,布布扣,bubuko.com
【Leetcode长征系列】Balanced Binary Tree
标签:io 数据 for ar 代码 ef leetcode on
原文地址:http://blog.csdn.net/u010239096/article/details/38535171