美文网首页LeetCode
965. 判断给定的二叉树是否唯一树

965. 判断给定的二叉树是否唯一树

作者: Liori | 来源:发表于2019-03-31 18:31 被阅读0次

    1. 问题

    A binary tree is univalued if every node in the tree has the same value.
    Return true if and only if the given tree is univalued.

    如果一棵二叉树中的每个节点的值都相等,则该二叉树是唯一树,返回 true。否则返回 false。

    2. 解题思路

    如果给定的二叉树是空的,则直接返回 true。否则,取出根节点的值,再对给定的二叉树做一个层序遍历,判断是否每个节点的值都等于根节点的值。

    3. 代码示例

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isUnivalTree(TreeNode root) {
            if (root == null) {
                return true;
            }
            
            int val = root.val;
            boolean reault = true;
            
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()) {
                TreeNode currentRoot = queue.poll();
                if(val != currentRoot.val) {
                    reault = false;
                    break;
                }
                
                if(currentRoot.left != null) {
                    queue.offer(currentRoot.left);
                }
                if(currentRoot.right != null) {
                    queue.offer(currentRoot.right);
                }
            }
                
            return reault;
        }
    }
    

    相关文章

      网友评论

        本文标题:965. 判断给定的二叉树是否唯一树

        本文链接:https://www.haomeiwen.com/subject/gouubqtx.html