LeetCode 965 Univalued Binary Tree

题意

判断二叉树是否是 唯一二叉树. 当树中所有节点的值都一样时,我们认为他是一颗 唯一二叉树

1
2
3
4
5
6
7
给予一棵树:
1
/ \
1 1
/ \
1 1
应当返回 `true`
1
2
3
4
5
6
7
给予一棵树:
1
/ \
1 1
/ \
5 1
应当返回 `false`

解法

这道题其实只是考一下对二叉树的遍历,我比较习惯用栈来实现,而不是递归,所以有以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 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) {
int i = root.val;

Stack<TreeNode> stack = new Stack<>();
stack.push(root);


while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.val != i) {
return false;
}
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}

return true;
}
}

Runtime: 1 ms, faster than 83.52% of Java online submissions for Univalued Binary Tree.

Memory Usage: 35.9 MB, less than 92.59% of Java online submissions for Univalued Binary Tree.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-965/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!