94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
非递归二叉树中序遍历
java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> inorderTraversal(TreeNode root) { 12 List<Integer> res = new ArrayList<>() ; 13 if (root == null) 14 return res ; 15 Stack<TreeNode> stack = new Stack<>() ; 16 TreeNode cur = root ; 17 while(cur != null || !stack.isEmpty()){ 18 while(cur != null){ 19 stack.push(cur) ; 20 cur = cur.left ; 21 } 22 TreeNode node = stack.pop() ; 23 res.add(node.val) ; 24 cur = node.right ; 25 } 26 return res ; 27 } 28 }
C++:
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 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode* root) { 13 vector<int> res ; 14 if (root == NULL) 15 return res ; 16 stack<TreeNode*> s ; 17 TreeNode* cur = root ; 18 while(cur != NULL || !s.empty()){ 19 while(cur != NULL){ 20 s.push(cur) ; 21 cur = cur->left ; 22 } 23 TreeNode* node = s.top() ; 24 s.pop() ; 25 res.push_back(node->val) ; 26 cur = node->right ; 27 } 28 return res ; 29 } 30 };