1 public List<Node> inOrder(Node root){ 2 List<Node> res = new LinkedList<Node>(); 3 Stack<Node> stack = new Stack<Node>(); 4 stack.push(root); 5 while(root!=null||!stack.isEmpty()){ 6 while(root){ 7 stack.push(root); 8 root= root.left; 9 } 10 Node tmp = stack.po...
Postorder与Inorder很相似,但是比Inorder复杂的地方是如何判断该节点的左右子树都已经访问过了,按照Inorder的写法左子树还是先被访问,没有问题,但是访问完左子树后不能直接访问当前节点,要判断当前节点的右子树是否已经被访问,如果没有访问则应该继续去访问右子树,最后再访问当前节点 1vector<int> postorderTraversal(Tr...
[LeetCode] 590. N-ary Tree Postorder Traversal_Easy [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal_Medium tag: Tree Traversal [LeetCode] 106. Construct Binary Tree from Postorder and Inorder Traversal_Medium tag: Tree Traversal [LeetCode] 331. Verify Preorder Serial...
1/*Recursive solution*/2classSolution {3public:4vector<int> inorderTraversal(TreeNode *root) {56vector<int>result;7inorderTraversal(root, result);89returnresult;10}1112voidinorderTraversal(TreeNode *root, vector<int>&result)13{14if(root == NULL)return;1516inorderTraversal(root->left, result...
Inorder 方法一:和Preorder方法一类似,直接做,但是需要一个计数器,第二次出栈的时候才可以输出。 classSolution {public: vector<int> inorderTraversal(TreeNode*root) { vector<int>res;if(root==NULL)returnres; unordered_map<TreeNode *,int> hash;//default value is 0;stack<TreeNode *>s({root})...
这道题的非递归解法跟上题的非递归解法基本一致,只是访问的节点时机不一样。详细分析可参考LeetCode上的一篇博文。具体程序如下: 1vector<int> inorderTraversal(TreeNode*root) {2vector<int>rVec;3stack<TreeNode *>st;4TreeNode *tree =root;5while(tree || !st.empty())6{7if(tree)8{9st.push(tr...
root->right=buildTree(inorder,i+1,to1,postorder,from2+i-from1,to2-1); return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1); ...
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { TreeNode *root = NULL; if(!inorder.size()) return root; this->inorder = inorder; this->postorder = postorder; for(int ci = 0; ci < inorder.size(); ci++) { if(inorder[ci] == postorder[postorder.size()-...
LeetCode之“树”:Binary Tree Preorder && Inorder && Postorder Traversal,BinaryTreePreorderTraversal题目链接题目要求:Givenabinarytree,returnthepreordertraversalofitsnodes'values.Forexample:Givenbinarytree{1...
2、postorder + inorder 1/**2* Definition for binary tree3* struct TreeNode {4* int val;5* TreeNode *left;6* TreeNode *right;7* TreeNode(int x) : val(x), left(NULL), right(NULL) {}8* };9*/10classSolution {11public:12typedef vector<int>::iterator Iter;1314TreeNode *build(...