preorder用栈两三下就写完了 1vector<int> preorderTraversal(TreeNode *root) {2vector<int>nodes;3if(root == NULL)returnnodes;4stack<TreeNode *>tStack;5tStack.push(root);6while(!tStack.empty()){7TreeNode *top =tStack.top();8nodes.push_back(top->val);9tStack.pop();10if(top->right...
详细分析可参考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(tree);10tree = tree->left;11}12else13{14tree =st.top();15rVec.push...
TreeNode* buildTree(vector<int>& preorder, int preBeg, vector<int>& inorder, int inBeg, int size) { if(size <= 0) return nullptr; TreeNode* curNode = new TreeNode(preorder[preBeg]); int inorderLeftTreeEnd = inBeg; while(inorder[inorderLeftTreeEnd] != preorder[preBeg]) ++in...
*/classSolution{public:vector<int>preorderTraversal(TreeNode*root){vector<int>ans;if(!root)returnans;stack<TreeNode*>s;s.push(root);while(!s.empty()){root=();s.pop();ans.push_back(root->val);if(root->right)s.push(root->right);if(root->left)s.push(root->left);}returnans;}}...
来自专栏 · LeetCode刷题 Construct Binary Tree from Preorder and Inorder Traversal 题目描述(中等难度) 根据二叉树的先序遍历和中序遍历还原二叉树。 解法一 递归 先序遍历的顺序是根节点,左子树,右子树。中序遍历的顺序是左子树,根节点,右子树。
总结: pre order tree ** Anyway, Good luck, Richardo! My code: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * }
链接:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ 难度:Medium 题目:105. Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a tree, construct the binary tree. ...
* 网址:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ * 结果:AC * 来源:LeetCode * 博客: ---*/#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;structTreeNode{intval; TreeNode *left; TreeNode *right;TreeNode(intx):val(x)...
:pencil2: 算法相关知识储备 LeetCode with Python :books:. Contribute to txywhjy/leetCode-2 development by creating an account on GitHub.
LeetCode 144. Binary Tree Preorder Traversal Solution1:递归版 二叉树的前序遍历递归版是很简单的,前序遍历的迭代版相对是最容易理解的。 迭代版链接:https://blog.csdn.net/allenlzcoder/article/details/79837841 Solution2:迭代版 前序遍历也是最简单的一种,分为下面三个步骤: 1...Leet...