LeetCode - Easy - 965. Univalued Binary Tree

r囧r小猫 2022-10-06 05:49 74阅读 0赞

Topic

  • Tree

Description

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

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.

Example 1:

d69d92fe4f185fc94c3a412acbbaca57.png

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

Example 2:

6313e28f6155836b9eee2b2b8b9e40a5.png

  1. Input: [2,2,2,5,2]
  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].

Analysis

方法一:递归法

方法二:迭代法

Submission

  1. import java.util.LinkedList;
  2. import com.lun.util.BinaryTree.TreeNode;
  3. public class UnivaluedBinaryTree {
  4. //方法一:递归法
  5. public boolean isUnivalTree(TreeNode root) {
  6. if(root == null) return true;
  7. if(root.left != null && root.left.val != root.val)
  8. return false;
  9. if(root.right != null && root.right.val != root.val)
  10. return false;
  11. return isUnivalTree(root.left) && isUnivalTree(root.right);
  12. }
  13. //方法二:迭代法
  14. public boolean isUnivalTree2(TreeNode root) {
  15. LinkedList<TreeNode> stack = new LinkedList<>();
  16. stack.push(root);
  17. while(!stack.isEmpty()) {
  18. TreeNode node = stack.pop();
  19. if(node.left != null) {
  20. if(node.left.val != root.val)
  21. return false;
  22. stack.push(node.left);
  23. }
  24. if(node.right != null) {
  25. if(node.right.val != root.val)
  26. return false;
  27. stack.push(node.right);
  28. }
  29. }
  30. return true;
  31. }
  32. }

Test

  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. import com.lun.util.BinaryTree;
  4. public class UnivaluedBinaryTreeTest {
  5. @Test
  6. public void test() {
  7. UnivaluedBinaryTree obj = new UnivaluedBinaryTree();
  8. assertTrue(obj.isUnivalTree(BinaryTree.integers2BinaryTree(1,1,1,1,1,null,1)));
  9. assertFalse(obj.isUnivalTree(BinaryTree.integers2BinaryTree(2,2,2,5,2)));
  10. }
  11. @Test
  12. public void test2() {
  13. UnivaluedBinaryTree obj = new UnivaluedBinaryTree();
  14. assertTrue(obj.isUnivalTree2(BinaryTree.integers2BinaryTree(1,1,1,1,1,null,1)));
  15. assertFalse(obj.isUnivalTree2(BinaryTree.integers2BinaryTree(2,2,2,5,2)));
  16. }
  17. }

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读