- Check Full Binary Tree
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here.
Full Binary Tree
1
/
2 3
/
4 5
Not a Full Binary Tree
1
/
2 3
/
4
Example
Example1
Input: {1,2,3}
Output: true
Explanation:
1
/
2 3
is a full binary tree.
Example2
Input: {1,2,3,4}
Output: false
Explanation:
1
/
2 3
/
4
is not a full binary tree
解法1:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the given tree
* @return: Whether it is a full tree
*/
bool isFullTree(TreeNode * root) {
if (!root) return true;
if (!root->left && !root->right) return true;
if (!root->left || !root->right) return false;
return isFullTree(root->left) && isFullTree(root->right);
}
};
代码同步在
https://github.com/luqian2017/Algorithm