Open Zheaoli opened 2 years ago
/*
* @lc app=leetcode id=100 lang=typescript
*
* [100] Same Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
if (!p && !q) {
return true;
}
return p?.val === q?.val
&& p?.left?.val === q?.left?.val
&& p?.right?.val === q?.right?.val
&& isSameTree(p?.left, q?.left)
&& isSameTree(p?.right, q?.right);
};
// @lc code=end
微信id: 弘树 来自 vscode 插件
class Solution {
Map<Integer, Integer> map = new HashMap<>();
int ans = 0;
public int widthOfBinaryTree(TreeNode root) {
dfs(root, 0, 0);
return ans;
}
private void dfs(TreeNode root, int row, int col) {
if (root == null) {
return;
}
if (!map.containsKey(row)) {
map.put(row, col);
}
ans = Math.max(ans, col - map.get(row) + 1);
dfs(root.left, row + 1, col << 1);
dfs(root.right, row + 1, col << 1 | 1);
}
}
WeChat: Saraad
2022-08-27