Balanced Binary Tree(leetcode)
2014-11-07 15:45
253 查看
题目:
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 of every node never differ by more than 1.
Show Tags
题目来源:https://oj.leetcode.com/problems/balanced-binary-tree/
解题思路:判断每个节点的孩子节点,如果深度差比1大,则不是平衡二叉树。定义没有孩子的节点的深度为0。然后用后序遍历,先遍历孩子再遍历父亲的办法来不断判断。
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 of every node never differ by more than 1.
Show Tags
题目来源:https://oj.leetcode.com/problems/balanced-binary-tree/
解题思路:判断每个节点的孩子节点,如果深度差比1大,则不是平衡二叉树。定义没有孩子的节点的深度为0。然后用后序遍历,先遍历孩子再遍历父亲的办法来不断判断。
#include<iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool postorderTraverse(TreeNode *root) { if(root==NULL) return true; if(postorderTraverse(root->left)==false) return false; if(postorderTraverse(root->right)==false) return false; int leftValue=(root->left==NULL)?-1:root->left->val; int rightValue=(root->right==NULL)?-1:root->right->val; if(abs(leftValue-rightValue)>1) return false; else root->val=max(leftValue,rightValue)+1; return true; } bool isBalanced(TreeNode *root) { return postorderTraverse(root); } int main() { TreeNode *root=new TreeNode(1); root->left=new TreeNode(2); root->right=new TreeNode(3); cout<<isBalanced(root)<<endl; system("pause"); return 0; }
相关文章推荐
- Leetcode: Balanced Binary Tree
- LeetCode(110)Balanced Binary Tree
- leetcode 1: balanced binary tree
- [leetcode]Balanced Binary Tree
- leetcode 110. Balanced Binary Tree 判断是否是一颗平衡二叉树
- Leetcode-110. Balanced Binary Tree
- LeetCode - Balanced Binary Tree
- [leetcode] Balanced Binary Tree
- [Leetcode 9] 110 Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree (平衡二叉树)
- 【Leetcode】110. Balanced Binary Tree 【DFS】
- [LeetCode]Balanced Binary Tree
- Leetcode[110]-Balanced Binary Tree
- leetcode No110. Balanced Binary Tree
- leetcode_c++:树:Balanced Binary Tree(110)
- Balanced Binary Tree——LeetCode
- [LeetCode] 110. Balanced Binary Tree
- leetcode — balanced-binary-tree
- [LeetCode]Balanced Binary Tree
- leetcode 之 Balanced Binary Tree