/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<TreeNode*> s;
vector<int> v;
while (root != NULL || !s.empty()) {
for (; root != NULL; root = root->left)
s.push_back(root);
v.push_back(s.back()->val);
root = s.back()->right;
s.pop_back();
}
return v;
}
};
Python Code:
classSolution:definorderTraversal(self,root: TreeNode) -> List[int]:ifnot root:return [] stack = [] ans = [] cur = rootwhile cur or stack:while cur: stack.append(cur) cur = cur.left cur = stack.pop() ans.append(cur.val) cur = cur.rightreturn ans
Java Code:
recursion
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {List<Integer> res =newLinkedList<>();publicList<Integer> inorderTraversal(TreeNode root) {inorder(root);return res; }publicvoidinorder (TreeNode root) {if (root ==null) return;inorder(root.left);res.add(root.val);inorder(root.right); }}
iteration
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicList<Integer> inorderTraversal(TreeNode root) {List<Integer> res =newArrayList<> ();Stack<TreeNode> stack =newStack<> ();while (root !=null||!stack.isEmpty()) {while (root !=null) {stack.push(root); root =root.left; } root =stack.pop();res.add(root.val); root =root.right; }return res; }}