LintCode 726: Check Full Binary Tree

  1. 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章