二叉树的边界。题意是给一个二叉树,请按逆时针方向输出二叉树边界上的节点。例子,
Example 2
Input: ____1_____ / \ 2 3 / \ / 4 5 6 / \ / \ 7 8 9 10 Ouput: [1,2,4,7,8,9,10,6,3] Explanation: The left boundary are node 1,2,4. (4 is the left-most node according to definition) The leaves are node 4,7,8,9,10. The right boundary are node 1,3,6,10. (10 is the right-most node). So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].
这个题需要分成几个部分做,分别是root节点,左边缘的节点,叶子节点,右边缘的节点。
首先将根节点的值放入一个数组[1],这没什么可说的;
再来是创建一个数组[2],用先序遍历找到所有的左边缘的节点,注意不要将左子树上的叶子节点加入,判断方法是看当前节点是否有左右孩子,如果没有,则直接return;
创建另一个数组[3],用后序遍历找到所有右边缘的节点,注意不要将右子树上的叶子节点加入,判断方法是看当前节点是否有左右孩子,如果没有,则直接return;
再创建一个数组[4],存放所有的叶子节点,判断方法是如果当前节点没有左右孩子,则他本身就是个叶子节点。
最后拼接如上的几个数组[1, 2, 3, 4]。
时间O(n)
空间O(h)
1 /** 2 * @param {TreeNode} root 3 * @return {number[]} 4 */ 5 var boundaryOfBinaryTree = function (root) { 6 var head = []; 7 var left = []; 8 var right = []; 9 var leaves = []; 10 var findLeft = function (root) { 11 if (root) { 12 // if it is a leaf node 13 if (root.left === null && root.right === null) { 14 return; 15 } 16 left.push(root.val); 17 if (root.left) { 18 findLeft(root.left); 19 } else { 20 findLeft(root.right); 21 } 22 } 23 } 24 25 var findRight = function (root) { 26 if (root) { 27 // if it is a leaf node 28 if (root.left === null && root.right === null) { 29 return; 30 } 31 if (root.right) { 32 findRight(root.right); 33 } else { 34 findRight(root.left); 35 } 36 right.push(root.val); 37 } 38 }; 39 40 var findLeaves = function (root) { 41 if (root) { 42 if (root.left === null && root.right === null) { 43 leaves.push(root.val); 44 } 45 findLeaves(root.left); 46 findLeaves(root.right); 47 } 48 }; 49 50 var group = function (root) { 51 if (root) { 52 head.push(root.val); 53 if (root.left) { 54 findLeft(root.left); 55 } 56 if (root.right) { 57 findRight(root.right); 58 } 59 if (root.left || root.right) { 60 findLeaves(root); 61 } 62 } 63 }; 64 group(root); 65 return [...head, ...left, ...leaves, ...right]; 66 };