Given a binary tree, return the inorder traversal of its nodes ' values.
For Example:given binary Tree [1,null,2,3]
,
1 2 / 3
Return [1,3,2]
.
Note: Recursive (Recursive) solution is trivial, could do it iteratively (iteration)?
Ideas:
Solution One: The recursive method is very simple,
(1) If root is empty, NULL is returned;
(2) If Root->left = NULL, returns the middle-order traversal element of the left subtree;
(3) If root->right = NULL, returns the middle-order traversal element of the right subtree;
(4) Finally, the left sub-tree in the middle sequence traversal elements into the container, root->val into the container, and then the right subtree of the middle sequence traversal elements into the container;
(5) Return to the container;
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int> Inordertraversal (treenode*root) { -vector<int>V, v1, v2; - inti; the if(Root = =NULL) - returnv; - if(Root->left! =NULL) -V1 = inordertraversal (root->Left ); + if(Root->right! =NULL) -V2 = Inordertraversal (root->Right ); + for(i =0; I < v1.size (); i++) A V.push_back (V1[i]); atV.push_back (root->val); - for(i =0; I < v2.size (); i++) - V.push_back (V2[i]); - returnv; -}
Solution Two: Non-recursive middle sequence traversal binary tree, to define a stack (stack)
1 classSolution {2 Public:3vector<int> Inordertraversal (treenode*root) {4vector<int>v;5Stack<treenode*>Node_stack;6treenode* Pnode =Root;7 while((Pnode! = NULL) | |!Node_stack.empty ()) {8 //node is not empty, joins the stack, and accesses the left subtree of the node9 if(Pnode! =NULL) {Ten Node_stack.push (pnode); OnePnode = pnode->Left ; A } - Else{ - //The node is empty, pops a node from the stack, accesses the node, thePnode =node_stack.top (); - Node_stack.pop (); -V.push_back (pnode->val); - //Access node right subtree +Pnode = pnode->Right ; - } + } A returnv; at } -};
Leetcode 94. Binary Tree inorder traversal (middle sequence traversal binary trees)