算法题:
- 链接:https://leetcode-cn.com/problems/same-tree/
- 描述:
- 给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。
- 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
- 解题
```javascript
/**
- @param {TreeNode} p
- @param {TreeNode} q
- @return {boolean}
*/
var isSameTree = function(p, q) {
if(p===null && q===null) {
} if (p===null || q===null) {return true
} if (p.val !==q.val) {return false
}return false
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right)
};
<a name="LbhHM"></a>### 手写题:- 链接:[https://bigfrontend.dev/zh/problem/virtual-dom-v-jsx-2](https://bigfrontend.dev/zh/problem/virtual-dom-v-jsx-2)- 解题:```javascriptfunction checkForClosing(str, i) {if (str[i] == "/") return true;if (str[i] == ">") return false;return checkForClosing(str, i + 1);}function parseChild(str) {console.log('str',str)console.log('===============')// str = str.trim();let child = [];let text = "";for (var i = 0; i < str.length; i++) {if (str[i] == "<" && checkForClosing(str, i)) {console.log('break')break;}if (str[i] == "<") {let newStr = str.slice(i);const result = parse(newStr);child.push(text);child.push(result);i += result.endClosing;text = "";continue;}else {text += str[i];}}console.log('outer')child.push(text);const nextTag = i;if (nextTag == 0) return [null, nextTag];return [child, nextTag];}function parseTag(str) {let isClosing = false;let closeOpening = str.indexOf(">");let tag = str.slice(1, closeOpening).trim();if (tag[0] == "/") {isClosing = true;tag = tag.slice(1).trim();}return [tag, closeOpening, isClosing]}function parse(code) {// your code herecode = code.trim();if (code[0] !== "<" || code[code.length - 1] !== ">") {throw new Error("");}if (code.split("<").length !== code.split(">").length) {throw new Error("");}let i = 1;var [opening, endOpening, isClosing] = parseTag(code, i);code = code.substr(endOpening + 1, code.length);i += endOpening;var [child, endChild] = parseChild(code, i);code = code.substr(endChild, code.length);i += endChild;var [closing, endClosing, isClosing] = parseTag(code, i);code = code.substr(endClosing + 1, code.length);i += endClosing;if (!isClosing) throw new Error("Closing element not found");if (opening !== closing) {throw new Error("Opening and closing doesn't match")}let res = {opening,child: [child],closing,endClosing: i}return res;}/*** @param {any} your AST* @returns {string}*/function generate(ast) {// your code hereif (ast.child[0] == null) {return h(`${ast.opening}`, null);} else {let childrens = ast.child[0];let newChildrens = []for (let i = 0; i < childrens.length; i++) {if (childrens[i] instanceof Object) {newChildrens.push(generate(childrens[i]))} else {childrens[i] != "" && newChildrens.push(childrens[i]);}}let opening;if (`${ast.opening}`[0] == `${ast.opening}`[0].toUpperCase()) {opening = Heading;} else {opening = `${ast.opening}`;}return h(opening, null, ...newChildrens);}}
- 自己没写出来,最后啃别人的代码啃懂了,还需要多练习几次。加强对源码的阅读和临摹,之前这是这块逻辑懂了,但是写起来太费劲了。整了一个下午
