今天在切leetcode的时候看到一个Morris算法,用来中序遍历二叉树,非递归,O(1)空间.觉得很强大.记录一下. 基本思想是利用了Threaded Binary Tree. 步骤如下: current节点设置为root.如果current不为空,到2,否则返回: 如果current没有左子树,输出current的值,current等于current.right: 如果current有左子树,首先找到current节点的precedent,也就是该节点左子树中最最右边那个节点.然后把最最右…
/* Author: Jiangong SUN */ Here I will introduce the breadth first traversal of binary tree. The principe is that you traverse the binary tree level by level. This traversal is quite different than depth first traversal. In depth first traversal you…
Process analysis Stack = 5,  Push 3, Stack = 5, 3.    Pre = 5 Current = 3, Pre = 5, Push 2 to the stack, stack = 5, 3, 2, Pre = 3 Current = 2, Pre = 3, pop 2, PRINT 2, Stack = 5, 3.  Pre = 2 Current = 3, push 4, Stack = 5, 3 , 4.  Pre = 3 Current = 4…
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? 一般我们提到树的遍历,最常见的有先序遍历,中序遍历,后序遍历和层序遍历,它们用递归实现起…
Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? 经典题目,求二叉树的后序遍历的非递归方法,跟前序,中序,层序一样都需要用到栈,后续的…
function createNode(value) { return { value, left: null, right: null }; } function BinaryTree(val) { return { root: null, nodes: [], add(val) { const node = createNode(val); if (!this.root) { this.root = node; } else { this.downShift(node); } this.no…
Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? 经典题目,求二叉树的后序遍历的非递归方法,跟前序,中序,层序一样都需要用到栈,后序的…
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 使用O(n)空间的话可以直接中序遍历来找问题节点. 如果是…
Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively? ----------------------------------------------------…
Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20…