日期 | 是否一次通过 | comment |
---|---|---|
2019-01-16 19:27 | 一次通过 | 本质是preOrder |
(来源: https://leetcode.com/problems/univalued-binary-tree/)
本质上就是个遍历啊
递归
class Solution {
public boolean isUnivalTree(TreeNode root) {
if(root == null) {
return true;
}
int[] tempNum = new int[]{root.val};
return helper(root, tempNum);
}
private boolean helper(TreeNode root, int[] tempNum) {
if(root == null) {
return true;
}
if(root.val != tempNum[0]) {
return false;
}
return helper(root.left, tempNum) && helper(root.right, tempNum);
}
}
非递归
class Solution {
public boolean isUnivalTree(TreeNode root) {
if(root == null) {
return true;
}
int tempNum = root.val;
Stack<TreeNode> nodeS = new Stack<>();
nodeS.push(root);
while(!nodeS.isEmpty()) {
TreeNode tempNode = nodeS.pop();
if(tempNode.val != tempNum) {
return false;
}
if(tempNode.right != null) {
nodeS.push(tempNode.right);
}
if(tempNode.left != null) {
nodeS.push(tempNode.left);
}
}
return true;
}
}
网友评论