/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root1 * @param {TreeNode} root2 * @return {boolean} */ var leafSimilar = function(root1, root2) { let r1 = morris(root1); let r2 = morris(root2); return r1.join(',') === r2.join(',') }; const morris=(root)=>{ let cur = root; let res = []; while(cur){ if(cur.left === null){ if(cur.right === null){ res.push(cur.val); } cur = cur.right; }else{ let node = cur.left; while(node && node.right !== null && node.right !== cur){ node = node.right; } if(node.right === null){ node.right = cur; cur = cur.left; }else{ if(node.left === null)res.push(node.val); node.right = null; cur = cur.right; } } } return res; }