摘要: 题目:Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure.两个结点被交换过了,那自然而然的想到找出两个结点就行了,而中序遍历又正好是升序序列,因此在中序遍历过程中找到两个不符合升序的结点即可,这里一定要保存一下前驱结点,刚开始没想到,捣鼓了半天过了一半case,后来才发现,代码: 1 void recoverTree(TreeNode *root) { 2 TreeNode* node1; 3 ... 阅读全文
posted @ 2013-11-24 17:22 月窟仙人 阅读(99) 评论(0) 推荐(0) 编辑
摘要: 题目:Given inorder and postorder traversal of a tree, construct the binary tree.跟之前的通过先序遍历和中序遍历构建二叉树一样,有个区别是,这次的根结点每次都从后序列表中从后向前扫。代码: 1 TreeNode *buildTree(vector &inorder, vector &postorder) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution ins... 阅读全文
posted @ 2013-11-24 13:56 月窟仙人 阅读(155) 评论(0) 推荐(0) 编辑
摘要: 题目:Given preorder and inorder traversal of a tree, construct the binary tree.通过先序遍历和中序遍历构造二叉树。大概思路是递归的构造,因为先序遍历总是先访问根结点,所以很容易从先序列表中得到根,位于该结点右侧的就是子树,再由这个根结点从中序列表中找到,位于该值左侧的就是左子树,右侧的即为又子树。然后分别用同样的方法构建左、右子树,直到构造完成。代码: 1 TreeNode *buildTree(vector &preorder, vector &inorder) { 2 // IMPORTANT... 阅读全文
posted @ 2013-11-24 13:54 月窟仙人 阅读(210) 评论(0) 推荐(0) 编辑