Binary Tree Inorder Traversal
Description
Given a binary tree, return the inorder traversal of its nodes' values.
Example Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,3,2].
Challenge
Can you do it without recursion?
- We are here
Link
Method
- DFS
- x
Example
- 1
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */ public: // iteration vector<int> inorderTraversal(TreeNode *root) { // write your code here if (!root) { return {}; } TreeNode* cur = root; vector<int> result; stack<TreeNode*> stk; // modified from standard DFS while (cur || !stk.empty()) { while (cur) { stk.push(cur); cur = cur->left; } cur = stk.top(); stk.pop(); result.push_back(cur->val); cur = cur->right; } return result; } };
Similar problems
x
Tags
x