摘要:
Given inorder and postorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.解法:递归求解,思路同上一篇博客中用先序和中序构造二叉树类似。 1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 ... 阅读全文
摘要:
Given preorder and inorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.解法:递归求解。 基本情况:先序与中序数组长度小于1时,返回NULL。 递归步骤:首先确定preorder的第一个元素一定是该树的root,再在inorder中找到该元素,标记为index,index左部为左子树的中序,右部为右子树的中序;随后通过左右子树中序的长度(可能为0),在preorder中确定左右子树的先序。 1 .. 阅读全文
摘要:
Given a binary tree, return theinordertraversal of its nodes' values.Note:Recursive solution is trivial, could you do it iteratively?二叉树中序遍历,非递归解法。使用栈记录中序遍历时中间节点的访问顺序,从栈中弹出的顺序即为中序。Program Runtime:16 milli secs 1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * Tr... 阅读全文