/** * 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} root * @return {void} Do not return anything, modify root in-place instead. */ import TreeNode from './tool'; const flatten = function (root) { }; /* 思路:直接先序遍历整个二叉树,将整个节点按照顺序存进数组最后遍历它们,把它们连接起来 */ function f1(root) { // 如果为空返回 if (!root) return root; const preNodes = [];// 储存先序遍历的数组 const dummyHead = new TreeNode(1); // 哑节点,用于构建链表 // 先序遍历 const stack = [root]; // 先序遍历需要用到的栈 while (stack.length) { const node = stack.pop(); // 取出根节点 preNodes.push(node); if (node.right) stack.push(node.right); if (node.left) stack.push(node.left); } // 将数组中所有的节点通过right链接到dummyHead let preNode = dummyHead; for (let i = 0; i < preNodes.length; i++) { preNodes[i].left = null; // 左节点滞空 preNode.right = preNodes[i]; preNode = preNodes[i]; } return dummyHead.right; } /* 利用栈来前序遍历,思路和上面迭代一致 */ function f2(root) { const preorderTraversal = (node, nodeList) => { if (node) { nodeList.push(node); preorderTraversal(node.left, nodeList); preorderTraversal(node.right, nodeList); } }; if (!root) return root; const list = []; // 递归遍历二叉树,把节点放进list中 preorderTraversal(root, list); // 将所有节点链接起来 const dummyHead = new TreeNode(-1); // 利用哑节点来处理头节点问题 let cur = dummyHead; for (let i = 0; i < list.length; i++) { cur.right = list[i]; cur.left = null; cur = list[i]; } return dummyHead.right; } /* 在前序遍历的同时设置节点,根据前序遍历的顺序,会先处理左子树,再处理右子树,所以只要先把右子树 压入栈中,再把左子树压入栈中,这样当所有的左子树处理完毕,会继续处理右子树 */ function f3(root) { if (!root) return root; const stack = [root]; // 要链接到的节点,初始为空,表示字节的的前面一个节点 let preNode = null; while (stack.length) { const node = stack.pop(); // 将当前节点链接到preNode.right if (preNode) { preNode.right = node; preNode.left = null; } // 将右子树压入栈中 if (node.right) stack.push(node.right); // 将左子树压入栈中 if (node.left) stack.push(node.left); preNode = node; } }