详细分析可参考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...
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:12vector<int> preorderTraversal(TreeNode *root) {13//IMPORTANT: Please reset any...
Given a binary tree, return thepreordertraversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 1. 2. 3. 4. 5. return [1,2,3]. Note:Recursive solution is trivial, could you do it iteratively? 2.解决方案1 classS...
Given a binary tree, return the preorder traversal of its nodes’ values. Can you do it without recursion? http://www.lintcode.com/en/problem/binary-tree-preorder-traversal/ 1.递归 /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode...
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); preorderTraversalHelper(root, list); return list; } private void preorderTraversalHelper(TreeNode root, List<Integer> list) { if (root == null) { return; } list.add(root.val); preorderTrav...
Construct Binary Tree from Preorder and Inorder Traversal 题目描述(中等难度) 根据二叉树的先序遍历和中序遍历还原二叉树。 解法一 递归 先序遍历的顺序是根节点,左子树,右子树。中序遍历的顺序是左子树,根节点,右子树。 所以我们只需要根据先序遍历得到根节点,然后在中序遍历中找到根节点的位置,它的左边就...
Morris traversal: My code: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{publicList<Integer>preorderTraversal(TreeNoderoot){List<Integer>ret=newArrayList<...
[TreeNode]()varcurr=rootwhile(stack.nonEmpty||curr!=null){while(curr!=null){stack.push(curr)rs.append(curr.value)curr=curr.left}valnode=stack.pop()curr=node.right}rs.toList}defpreorderTraversalV4(root:TreeNode):List[Int]={if(root==null)returnNilvalrs=ListBuffer.empty[Int]valstack=Stack...
Binary tree traversal: Preorder, Inorder, and Postorder In order to illustrate few of the binary tree traversals, let us consider the below binary tree: Preorder traversal: To traverse a binary tree in Preorder, following operations are carried-out (i) Visit the root, (ii) Traverse the le...
Preorder Traversal: Sample Solution: Java Code: classNode{intkey;Nodeleft,right;publicNode(intitem){// Constructor to create a new Node with the given itemkey=item;left=right=null;}}classBinaryTree{Noderoot;BinaryTree(){// Constructor to create an empty binary treeroot=null;}voidprint_Pre...