1. 程式人生 > 實用技巧 >[LeetCode] 965. Univalued Binary Tree 單值二叉樹

[LeetCode] 965. Univalued Binary Tree 單值二叉樹


A binary tree isunivaluedif every node in the tree has the same value.

Returntrueif and only if the given tree is univalued.

Example 1:

Input: [1,1,1,1,1,null,1]
Output: true

Example 2:

Input: [2,2,2,5,2]
Output: false

Note:

  1. The number of nodes in the given tree will be in the range[1, 100].
  2. Each node's value will be an integer in the range[0, 99]
    .

這道題定義了一種單值二叉樹,需要二叉樹中所有的結點值相同。先給了一棵二叉樹,問是不是單值二叉樹。其實就是考察遍歷二叉樹,當然遞迴的方法在寫法上最簡單了。這裡可以將每個結點值都跟根結點值進行比較,只要任意一個不相同,則表示不是單值二叉樹。所以需要將根結點值當個引數代入遞迴函式,所以寫一個 helper 函式,進行先序遍歷的遞迴寫法即可,參見程式碼如下:


解法一:

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        return helper(root, root->val);
    }
    bool helper(TreeNode* node, int val) {
        if (!node) return true;
        if (node->val != val) return false;
        return helper(node->left, val) && helper(node->right, val);
    }
};

當然我們也可以不寫額外的子函式,在一個函式比較,只要任意一個結點的左右子結點值(存的的話)均和其父結點值相等,則一定是單值二叉樹。所以在一個函式中也可以進行比較,參見程式碼如下:


解法二:

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if (!root) return true;
        if (root->left && root->left->val != root->val) return false;
        if (root->right && root->right->val != root->val) return false;
        return isUnivalTree(root->left) && isUnivalTree(root->right);
    }
};

上面的解法都是遞迴寫法,來看迭代寫法的層序遍歷吧,解題思路並沒有什麼不同,就只是遍歷的方法不同而已,參見程式碼如下:


解法三:

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if (!root) return true;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            TreeNode* t = q.front(); q.pop();
            if (t->val != root->val) return false;
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
        }
        return true;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/965


類似題目:

Find All The Lonely Nodes


參考資料:

https://leetcode.com/problems/univalued-binary-tree/

https://leetcode.com/problems/univalued-binary-tree/discuss/211190/JavaC%2B%2BPython-Straight-Forward

https://leetcode.com/problems/univalued-binary-tree/discuss/252904/C%2B%2B-4-Lines-of-Code-Beats-100-Easy-to-Understand

https://leetcode.com/problems/univalued-binary-tree/discuss/211397/JavaPython-3-BFS-and-DFS-clean-codes-w-brief-analysis.


LeetCode All in One 題目講解彙總(持續更新中...)