<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Binary Tree on Yosgi</title><link>https://yosgi.github.io/en/tags/binary-tree/</link><description>Recent content in Binary Tree on Yosgi</description><generator>Hugo</generator><language>en</language><lastBuildDate>Mon, 29 Jun 2026 09:20:51 +0000</lastBuildDate><atom:link href="https://yosgi.github.io/en/tags/binary-tree/index.xml" rel="self" type="application/rss+xml"/><item><title>1104-Binary Tree Pathfinding</title><link>https://yosgi.github.io/en/post/1104-binary-tree-pathfinding/</link><pubDate>Thu, 29 Jul 2021 00:00:00 +1200</pubDate><guid>https://yosgi.github.io/en/post/1104-binary-tree-pathfinding/</guid><description>The first thing I thought of was to construct a binary tree, and then use the symmetric relationship of each layer to find the parent node var pathInZigZagTree = function(label) { let stack = [] for (let i = 1; i &lt;= label; i++) { let level = Math.floor(Math.log(i) / Math.log(2)) if (!stack[level]) { stack[level] = [] } if (level % 2 === 0) { stack[level].push(i) } else { stack[level].unshift(i) } } var level = Math.floor(Math.log(label) / Math.log(2)) let ans = [] while (level) { ans.push(label) level-- label = Math.floor(label / 2) let index = stack[level].length - 1 - stack[level].indexOf(label) label = stack[level][index] } ans.push(1) return ans.reverse() }Sorry, timeout. Inspired by the answer, since it is symmetrical, the sum of the symmetrical numbers is the same when the number of layers is the same.</description></item><item><title>865 - Minimum subtree with all deepest nodes</title><link>https://yosgi.github.io/en/post/865-minimum-subtree-with-all-deepest-nodes/</link><pubDate>Sun, 21 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/865-minimum-subtree-with-all-deepest-nodes/</guid><description>Time: 60 minutes I was misled by the depth of the question and thought that the calculation depth should be done from top to bottom. In fact, it can be done from bottom to top. If the left and right subtrees have the same height, return the node itself and its depth. If the left subtree is deeper, it means that the smallest and deepest part is in the left subtree. Return the left subtree and its own depth.</description></item><item><title>783-Binary Search Tree Node Minimum Distance</title><link>https://yosgi.github.io/en/post/783-binary-search-tree-node-minimum-distance/</link><pubDate>Thu, 18 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/783-binary-search-tree-node-minimum-distance/</guid><description>Time: 10 minutes Solve by using the property of pre-order traversal of binary tree var minDiffInBST = function(root) { var min = Infinity var pre = null var dfs = function (root) { if (!root) return if (root.left) { dfs(root.left) } if (pre == null) { pre = root.val } else { console.log(pre,root.val) var reduce = Math.abs(pre - root.val) min = Math.min(min,reduce) pre = root.val } if (root.right) { dfs(root.right) } } dfs(root) return min };</description></item><item><title>814-Binary Tree Pruning</title><link>https://yosgi.github.io/en/post/814-binary-tree-pruning/</link><pubDate>Wed, 17 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/814-binary-tree-pruning/</guid><description>Time: 6 minutes It’s very simple. In-order traversal, calculate whether the value 1 exists in the subtrees on both sides, and remove it if not. If the left or right subtree or the tree itself contains 1, return true. Otherwise, return false. var pruneTree = function(root) { var DFS = function (root) { if (!root) return false var left = DFS(root.left) var right = DFS(root.right) if (!left) { root.left = null } if (!right) { root.right = null } if (left) { return true } if (right) { return true } if( root.val === 1) { return true } } var dummp = new TreeNode(1) dummp.left = root DFS(dummp) return dummp.left};One point to note is that the root itself may also need to be pruned, so a virtual node is added as the parent node</description></item><item><title>1448-Count the number of good nodes in a binary tree</title><link>https://yosgi.github.io/en/post/1448-count-the-number-of-good-nodes-in-a-binary-tree/</link><pubDate>Wed, 17 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/1448-count-the-number-of-good-nodes-in-a-binary-tree/</guid><description>Notes on counting good nodes in a binary tree using DFS with a running max.</description></item><item><title>1325-Delete the leaf node of the given value</title><link>https://yosgi.github.io/en/post/1325-delete-the-leaf-node-of-the-given-value/</link><pubDate>Wed, 17 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/1325-delete-the-leaf-node-of-the-given-value/</guid><description>Post-order traversal approach to delete target-valued leaf nodes using a dummy root.</description></item><item><title>1022 - the sum of the binary numbers from root to leaf</title><link>https://yosgi.github.io/en/post/1022-the-sum-of-the-binary-numbers-from-root-to-leaf/</link><pubDate>Wed, 17 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/1022-the-sum-of-the-binary-numbers-from-root-to-leaf/</guid><description>Time: 10 minutes The preorder is calculated from top to bottom, there is nothing much to say Converting binary to decimal is quite difficult, so I just parseInt(path, 2) var sumRootToLeaf = function(root) { var ans = 0 var dfs = function (root,path) { if (!root) return path += root.val if (!root.left &amp;&amp; !root.right) { ans += parseInt(path, 2) } root.left &amp;&amp; dfs(root.left,path) root.right &amp;&amp; dfs(root.right,path) } dfs(root,'') return ans };Time: 10 minutes The preorder is calculated from top to bottom, there is nothing much to say Converting binary to decimal is quite difficult, so I just parseInt(path, 2) var sumRootToLeaf = function(root) { var ans = 0 var dfs = function (root,path) { if (!root) return path += root.val if (!root.left &amp;&amp; !root.right) { ans += parseInt(path, 2) } root.left &amp;&amp; dfs(root.left,path) root.right &amp;&amp; dfs(root.right,path) } dfs(root,'') return ans };</description></item><item><title>563-Slope of Binary Tree</title><link>https://yosgi.github.io/en/post/563-slope-of-binary-tree/</link><pubDate>Tue, 16 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/563-slope-of-binary-tree/</guid><description>Time: 15 minutes Time: 15 minutes My first reaction when I got the question was to use recursion, but after I started writing it, I found that The condition that recursion needs to meet is that the problem can be split into sub-problems, but according to the meaning of the question, what we need to find is the difference between the sum of the left and right nodes of each node. This “sum of the left and right nodes” is a different problem for each node.</description></item><item><title>129-Find the sum of numbers from the root node to the leaf node</title><link>https://yosgi.github.io/en/post/129-find-the-sum-of-numbers-from-the-root-node-to-the-leaf-node/</link><pubDate>Tue, 16 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/129-find-the-sum-of-numbers-from-the-root-node-to-the-leaf-node/</guid><description>The question is about starting from the root node. The first thing that comes to mind is top-down DFS, passing parameters downward, and the end condition has no left or right children. Start with the pre-order traversal, and you can assume that all the previous nodes have been processed. var sumNumbers = function(root) { var ans = 0 var DFS = function (root,path) { if (!root) return path += root.val if (!root.left &amp;&amp; !root.right) { ans += Number(path) } root.left &amp;&amp; DFS(root.left,path) DFS(root.right, path) } DFS(root,'') return ans };The question is about starting from the root node. The first thing that comes to mind is top-down DFS, passing parameters downward, and the end condition has no left or right children.</description></item><item><title>124-Maximum Path Sum in a Binary Tree</title><link>https://yosgi.github.io/en/post/124-maximum-path-sum-in-a-binary-tree/</link><pubDate>Mon, 15 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/124-maximum-path-sum-in-a-binary-tree/</guid><description>Time: 30 minutes Once you understand the question, you can actually do it quickly. The question is about the value of any node. We can find the value of each node and choose the largest one. Since the path cannot return, we know that the path of the child node of the root node we start from can only choose left or right, or neither, and the result is x When finding max, compare x with the case where both sides are selected.</description></item><item><title>99-Restore Binary Search Tree</title><link>https://yosgi.github.io/en/post/99-restore-binary-search-tree/</link><pubDate>Sat, 13 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/99-restore-binary-search-tree/</guid><description>Time: 60 minutes The idea is still in-order traversal, using pre to cache the previous node. Because the in-order traversal is incremental, you must find the larger one first and then the smaller one. So the first problem is pre, the second is root var recoverTree = function(root) { var left = null var right = null var pre = null // You must find the big one first, then the small one, so the first one to have a problem is pre, and the second one to have a problem is root var DFS = function (root) { if (root.left) { DFS(root.left) } if (pre) { console.log(pre.val) if (pre.val &gt; root.val) { if(!left) { left = pre right = root } else { right = root } } pre = root } else { pre = root } if (root.right) { DFS(root.right) } } DFS(root) if (left &amp;&amp; right) { [left.val,right.val] = [right.val,left.val] } return root}</description></item><item><title>98-Verify Binary Search Tree</title><link>https://yosgi.github.io/en/post/98-verify-binary-search-tree/</link><pubDate>Sat, 13 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/98-verify-binary-search-tree/</guid><description>Time: 10 minutes Just use the increasing property of in-order traversal of the binary search tree In-order traversal to find the left child Does pre exist? If not, assign , find the right child, and return 1 If it exists, is it less than val? If yes, do not increment, and return false If not, increment, assign pre, and return 1 var isValidBST = function(root) { var preVal = null var DFS = function(root) { var left = true var right = true if (root.left) { left = DFS(root.left) } if (preVal !== null) { if (preVal &gt;= root.val) return false preVal = root.val } else { preVal = root.val } if (root.right) { right = DFS(root.right) } return left &amp;&amp; right } return DFS(root) };</description></item><item><title>863-All nodes with distance -K- in a binary tree</title><link>https://yosgi.github.io/en/post/863-all-nodes-with-distance-k-in-a-binary-tree/</link><pubDate>Sat, 13 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/863-all-nodes-with-distance-k-in-a-binary-tree/</guid><description>Time: 60 minutes The idea is still very simple. First use DFS to add a parent to each node, and find the required target by the way. Then starting from the target, use DFS to find a point K away from the target. Find all the parents of target in turn and use DFS to find the point with a distance K. The reason why it takes so much time is that after finding the parent, DFS is used to find it back, causing a memory overflow.</description></item><item><title>662-Binary Tree Maximum Width</title><link>https://yosgi.github.io/en/post/662-binary-tree-maximum-width/</link><pubDate>Sat, 13 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/662-binary-tree-maximum-width/</guid><description>Time: 120 minutes The initial idea was to use BFS, and remove a whole queue when removing it (later I learned that this is called breadth traversal) Then the double pointer finds the left and right nodes. End when both the left and right nodes do not exist var widthOfBinaryTree = function(root) { var que = [root] var max = 0 while(que.length) { var len = que.length var left = 0 var right = que.length - 1 while(!que[left] &amp;&amp; left &lt; len) { left ++ } while(!que[right] &amp;&amp; right &gt;= 0) { right -- } if (left &gt; right) { break } max = Math.max(max,right - left+ 1) for(let i = 0 ; i &lt; len ; i ++) { var node = que.shift() if (!node) { que.push(node) que.push(node) continue } node.left ? que.push(node.left) : que.push(null) node.right ? que.push(node.right) : que.push(null) } } return max };Soon, the submission showed that the execution exceeded the time limit, so a queue for storing sequence numbers was added, which was synchronized with the BFS stack to calculate the left and right distances.</description></item><item><title>222-Number of nodes in a complete binary tree</title><link>https://yosgi.github.io/en/post/222-number-of-nodes-in-a-complete-binary-tree/</link><pubDate>Sat, 13 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/222-number-of-nodes-in-a-complete-binary-tree/</guid><description>Time: 80 minutes The first reaction when I got the question was of course to solve it with DFS. But this is a complete binary tree, so we should use the properties of a complete binary tree. You can examine the depth of the left and right subtrees of the binary tree If the left depth is greater than the right depth, it means that the right side is full. The number of full nodes is 2 to the power of n - 1, plus the root is 2 to the power of n, and continue recursively on the left side.</description></item><item><title>669-Pruning a Binary Search Tree</title><link>https://yosgi.github.io/en/post/669-pruning-a-binary-search-tree/</link><pubDate>Thu, 11 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/669-pruning-a-binary-search-tree/</guid><description>#669. Pruning a binary search tree Release Date: March 11, 2021 Time: 20 minutes Similar to the previous question, most of them are divided into situations where the parent node is in the interval and not in the interval var trimBST = function(root, low, high) { var add = function (root,node) { if (!node || !root) return null if (node.val &gt; root.val ) { if (!root.right) { root.right = node } else { add(root.right,node) } } if (node.val &lt; root.val) { if (!root.left) { root.left = node } else { add(root.left,node) } } } var walk = function (root) { if (!root) return root if (root.val &lt; low || root.val &gt; high) { var left = walk(root.left) var right = walk(root.right) if (!left &amp;&amp; !right) { root = null } else if (right &amp;&amp; left) { root = right add(root,left) } else if (left) { root = left } else { root = right } } else { root.left= walk(root.left) root.right = walk(root.right) } return root } return walk(root) };After reading the analysis, I found that it can be simpler. The idea is that if it is greater than the right boundary, look directly in the left branch; if it is less than the left boundary, look directly in the right branch. This saves the step of deleting the node.</description></item><item><title>450-Delete a node in a binary search tree</title><link>https://yosgi.github.io/en/post/450-delete-a-node-in-a-binary-search-tree/</link><pubDate>Thu, 11 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/450-delete-a-node-in-a-binary-search-tree/</guid><description>Time: 30 minutes The question is divided into two parts to be solved, search and delete The search part is to find the node. You can find the required node according to the properties of the binary search tree. There are three types of deletion If there is only a left child, replace it with the left child. If there is only a right child, replace it with the right child. If there is neither child, assign null. (Since there was a recursive assignment earlier, this will succeed.) If there are both children, store the left child, replace it with the right child, and then find the left child’s position on the right. var deleteNode = function(root, key) { function insert(root,node) { if (root.val &gt; node.val) { if (!root.left) { root.left = node } else { insert(root.left,node) } } else { if (!root.right) { root.right = node } else { insert(root.right,node) } } } function search(root) { if (!root) { return null } if (root.val &gt; key) { root.left = search(root.left) } else if (root.val &lt; key){ root.right = search(root.right) } else { if (!root.left &amp;&amp; !root.right) { root = null } else if (root.left &amp;&amp; root.right) { var left = root.left root = root.right insert(root,left) } else if (root.left) { root = root.left } else if (root.right) { root = root.right } } return root } return search(root) };Points to note</description></item><item><title>116-Fill in the next right node pointer of each node</title><link>https://yosgi.github.io/en/post/116-fill-in-the-next-right-node-pointer-of-each-node/</link><pubDate>Wed, 10 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/116-fill-in-the-next-right-node-pointer-of-each-node/</guid><description>Time: 25 minutes The main idea is to use the stack. The difference from the ordinary level-order traversal is that the stack is cleared every time var connect = function(root) { if (!root) return null var stack = [root] while(stack.length) { var _stack = [...stack,null] stack = [] var pre = _stack.shift() while(_stack.length || pre) { pre.left &amp;&amp; stack.push(pre.left) pre.right &amp;&amp; stack.push(pre.right) pre.next = _stack.shift() pre = pre.next } } return root};Obviously, the memory space of On I used does not meet the constant space requirement of the question, considering that the links of each layer can be found in the form of a linked list by relying on the parent node.</description></item><item><title>1008-Pre-order traversal to construct a binary search tree</title><link>https://yosgi.github.io/en/post/1008-pre-order-traversal-to-construct-a-binary-search-tree/</link><pubDate>Wed, 10 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/1008-pre-order-traversal-to-construct-a-binary-search-tree/</guid><description>Time: Not done The main reason I didn’t make it was that I kept thinking about how to use a stack. When I looked at the answer to the stack later, I found that recursion was the simplest. recursion The idea is very simple. First, write out how to insert a child node. If the node is smaller than the parent node and the parent node’s left node is empty, make it the left node. If the node is larger than the parent node and the parent node’s right node is empty, make it the right node. If the node is smaller than the parent node, assign the parent node to the parent node’s left node and return to 1. If the node is larger than the parent node, assign the parent node to the parent node’s right node and return to 1. Traverse the entire array and insert each node one by one to get the result. var bstFromPreorder = function(preorder) { var add = function (node,val) { if (val &lt; node.val &amp;&amp; !node.left) { node.left = new TreeNode(val) } if (val &gt; node.val &amp;&amp; !node.right) { node.right = new TreeNode(val) } if (val &lt; node.val) { add(node.left,val) } if (val &gt; node.val) { add(node.right,val) } } var root = new TreeNode(preorder.shift()) for(let i = 0 ; i &lt; preorder.length ; i ++) { add(root,preorder[i]) } return root};Time: Not done</description></item><item><title>894-All possible full binary trees</title><link>https://yosgi.github.io/en/post/894-all-possible-full-binary-trees/</link><pubDate>Sun, 07 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/894-all-possible-full-binary-trees/</guid><description>Time: I copied the answers and finished it. It is easy to see that the idea is to use recursion, but the coding is the real problem. What we need to return is the root node, but the recursion is from bottom to top Try to solve it using dynamic programming, where dp(n) is the combination of dp(x) and dp (n - x - 1) var allPossibleFBT = function(n) { var dp = [] var buld = function (n) { for(let i = 1 ; i &lt;= n ; i ++ ) { if (i === 1) { dp[i] = new TreeNode(0) } else if (i % 2 === 0) { dp[i] = undefined } else { dp[i] = [] for(let left = 1; left &lt; i; left ++) { var leftNodes = dp[left] var rightNodes = dp[i - left - 1] for(let j = 0 ; j &lt; leftNodes.length ; j ++) { for(let k = 0 ; k &lt; rightNodes.length ; k ++) { var node = new TreeNode(0) node.left = leftNodes[j] node.right = rightNodes[k] dp[i].push(node) } } } } } } buld(n) return dp[n] };</description></item><item><title>297-Serialization and Deserialization of Binary Trees</title><link>https://yosgi.github.io/en/post/297-serialization-and-deserialization-of-binary-trees/</link><pubDate>Thu, 04 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/297-serialization-and-deserialization-of-binary-trees/</guid><description>Time: 30 minutes Serialization is simple and can be solved using BFS Deserialization requires the use of the properties of a binary tree, that is, the child nodes of the i-th node are (i + 1) * 2 - 1 and (i + 1) * 2 respectively. Find the parent node and push it onto the stack. At this point, pointer i is at the parent node’s val. Pop the parent node from the stack and find the parent node’s left and right nodes. The pointers find their values twice according to the rules. Push the left and right nodes onto the stack. i++ Repeat 1. var serialize = function(root) { if (!root) return [] var que = [root] var res = [] while(que.length) { var cur = que.shift() if (cur) { res.push(cur.val); que.push(cur.left); que.push(cur.right); } else { res.push('null'); } } return res.join(',') };/** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */var deserialize = function(data) { if (!data.length) return null var nodes = data.split(',') var i = 0 var root = new TreeNode(nodes[i]) var que = [root] while ( que.length) { var node = que.shift() var left = nodes[ (i + 1) * 2 - 1] var right = nodes[ (i + 1) * 2] if (left !== 'null') { node.left = new TreeNode(left) que.push(node.left) } else { node.left = null } if (right !== 'null') { node.right = new TreeNode(right) que.push(node.right) } else { node.right = null } i++ } return root};</description></item><item><title>1372-Longest Alternating Path in a Binary Tree</title><link>https://yosgi.github.io/en/post/1372-longest-alternating-path-in-a-binary-tree/</link><pubDate>Mon, 01 Mar 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/1372-longest-alternating-path-in-a-binary-tree/</guid><description>Time: 25 minutes In fact, this is a relatively common DFS type question. The reason why it took so long is because there was a problem in judging the boundary value. When starting from the root, since the root may not have child nodes, the len value is 0 Starting from the child node, since the child nodes have been judged, it is considered that there is an edge of length 1 from the current node to the next node, so it is 1</description></item><item><title>Summary of Binary Trees</title><link>https://yosgi.github.io/en/post/summary-of-binary-trees/</link><pubDate>Sun, 28 Feb 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/summary-of-binary-trees/</guid><description>When traversing a binary tree in front, middle, or post-order, we use a stack to simplify operations. This is because they are all recursive structures of DFS, which means processing from bottom to top. However, I always start writing code from the root node, so I need a stack, and the stack is first-in-first-out. This way, I can process the root node last. Level-order traversal is BFS, from top to bottom. The root element that was enqueued first is also the one I want to process first. This is why DFS uses a stack and BFS uses a queue.</description></item><item><title>102 - Level-order Traversal of a Binary Tree</title><link>https://yosgi.github.io/en/post/102-level-order-traversal-of-a-binary-tree/</link><pubDate>Sun, 28 Feb 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/102-level-order-traversal-of-a-binary-tree/</guid><description>Techniques and examples for breadth-first (level-order) traversal of binary trees.</description></item><item><title>145-Post-order traversal of a binary tree</title><link>https://yosgi.github.io/en/post/145-post-order-traversal-of-a-binary-tree/</link><pubDate>Fri, 26 Feb 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/145-post-order-traversal-of-a-binary-tree/</guid><description>1h The order of in-order traversal is left - right - center recursion It’s very easy with recursion var postorderTraversal = function(root) { var res = [] if (!root) return res var travel = function (node) { node.left &amp;&amp; travel(node.left) node.right &amp;&amp; travel(node.right) res.push(node.val) } travel(root) return res }; ```Iteration 1. Push the root node onto the stack. 1. Determine whether a node can be popped. If so, record itself as the node that was popped and pop it. 1. If a node cannot be popped, push the right and left nodes onto the stack. 1. Repeat step 2. ```javascript var postorderTraversal = function(root) { var stack = [root] var res = [] if (!root) { return res } var pre = root while(stack.length) { var node = stack[stack.length - 1] // When the left/right node of a node is the last node to be output, it means that both the left and right nodes have been output (because the root node is at the end of the post-order traversal) if ( (!node.left &amp;&amp; !node.right) || (node.left === pre || node.right === pre)) { // Only when there is no left or right node, or both left and right nodes have been output, can node = stack.pop() be output. pre = node res.push(node.val) } else { if (node.right) { stack.push(node.right) } if(node.left) { stack.push(node.left) } } } return res }; ```Summarize Although I have completed the forward, in-order, and post-order traversal of a binary tree, I have a feeling that I will forget it soon, especially the in-order and post-order traversal. I have not found any similarities between the two, so I will make a summary later. 1h The order of in-order traversal is left - right - center recursion It's very easy with recursion ```javascript var postorderTraversal = function(root) { var res = [] if (!root) return res var travel = function (node) { node.left &amp;&amp; travel(node.left) node.right &amp;&amp; travel(node.right) res.push(node.val) } travel(root) return res }; ```Iteration 1. Push the root node onto the stack. 1. Determine whether a node can be popped. If so, record itself as the node that was popped and pop it. 1. If a node cannot be popped, push the right and left nodes onto the stack. 1. Repeat step 2. ```javascript var postorderTraversal = function(root) { var stack = [root] var res = [] if (!root) { return res } var pre = root while(stack.length) { var node = stack[stack.length - 1] // When the left/right node of a node is the last node to be output, it means that both the left and right nodes have been output (because the root node is at the end of the post-order traversal) if ( (!node.left &amp;&amp; !node.right) || (node.left === pre || node.right === pre)) { // Only when there is no left or right node, or both left and right nodes have been output, can node = stack.pop() be output. pre = node res.push(node.val) } else { if (node.right) { stack.push(node.right) } if(node.left) { stack.push(node.left) } } } return res }; ```Summarize Although I've completed the forward, in-order, and post-order traversals of a binary tree, I have a feeling I'll soon forget them. This is especially true for the in-order and post-order traversals. I haven't found any similarities between them, so I'll summarize them later.</description></item><item><title>94-In-order traversal of a binary tree</title><link>https://yosgi.github.io/en/post/94-in-order-traversal-of-a-binary-tree/</link><pubDate>Thu, 25 Feb 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/94-in-order-traversal-of-a-binary-tree/</guid><description>30min The order of in-order traversal is left - middle - right recursion It’s very easy with recursion var inorderTraversal = function(root) { var res = [] if (!root) { return res } var travel = function (node) { node.left &amp;&amp; travel(node.left) res.push(node.val) node.right &amp;&amp; travel(node.right) } travel(root) return res }; ```Iteration The iterative steps are more complicated because the root node is not output first, so the root node needs to be retained 1. Push the root node onto the stack and check if it has a left child. If so, continue pushing until you reach a leaf node. 1. Pop the stack, output, and check if it has a right child. If so, push it onto the stack and continue with step 2. ```javascript var inorderTraversal = function(root) { var stack = [] var res = [] if (!root) return res stack.push(root) while(root.left) { stack.push(root.left) root = root.left } while(stack.length) { // At this point the top of the stack is the leftmost node in the tree var node = stack.pop() res.push(node.val) // There is a right node, push it into the stack and continue to look for the left node if (node.right) { node = node.right stack.push(node) while(node.left) { stack.push(node.left) node = node.left } } } return res };</description></item><item><title>144-Pre-order traversal of a binary tree</title><link>https://yosgi.github.io/en/post/144-pre-order-traversal-of-a-binary-tree/</link><pubDate>Thu, 25 Feb 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/144-pre-order-traversal-of-a-binary-tree/</guid><description>10min The order of pre-order traversal of a binary tree is center-left-right First traverse all root nodes and left nodes, then process the right node It can be seen that this is a recursive behavior. Recursive problems can be simplified using stacks. Iterative solution var preorderTraversal = function(root) { if (!root) return null var stack = [root] var res = [] while(stack.length) { var node = stack.pop() res.push(node.val) node.right &amp;&amp; stack.push(node.right) node.left &amp;&amp; stack.push(node.left) } return res };Recursive solution Recursive problems can of course be solved recursively var preorderTraversal = function(root) { var res = [] if (!root) return res var travel = function (node) { res.push(node.val) node.left &amp;&amp; travel(node.left) node.right &amp;&amp; travel(node.right) } travel(root) return res };10min</description></item><item><title>105-Constructing a binary tree from pre-order and in-order traversal sequences-1</title><link>https://yosgi.github.io/en/post/105-constructing-a-binary-tree-from-pre-order-and-in-order-traversal-sequences-1/</link><pubDate>Wed, 27 Jan 2021 00:00:00 +1300</pubDate><guid>https://yosgi.github.io/en/post/105-constructing-a-binary-tree-from-pre-order-and-in-order-traversal-sequences-1/</guid><description>Time: 40 minutes ####105. Construct a binary tree from pre-order and in-order traversal sequences recursion Pre-order traversal: center-left-right In-order traversal: left-middle-right Therefore, we can first find the root element from the pre-order traversal, and then determine the number of left and right subtrees from the in-order traversal. var buildTree = function(preorder, inorder) { if (preorder.length === 0 || inorder.length=== 0) return null let nodeVal = preorder.shift() let node = new TreeNode(nodeVal) let index = inorder.indexOf(nodeVal) node.left = buildTree(preorder.slice(0,index), inorder.slice(0,index)) node.right = buildTree(preorder.slice(index),inorder.slice(index + 1)) return node }; ```Optimization Slices are very performance-intensive. In fact, there is no need to pass arrays. Functions can just pass pointers. ```javascript var buildTree = function(preorder, inorder) { var helper = function (p_start,p_end,i_start,i_end) { if (p_start &gt; p_end || i_start &gt; i_end ) return null let nodeVal = preorder[p_start] let node = new TreeNode(nodeVal) let index = inorder.indexOf(nodeVal) let left = index - i_start node.left = helper(p_start + 1 , p_start + left , i_start ,index - 1) node.right = helper(p_start + left + 1,p_end, index + 1,i_end) return node } return helper(0,preorder.length - 1,0,preorder.length - 1) };Summarize:</description></item></channel></rss>