Given a binary tree, return the inorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
二叉树中序非递归遍历,使用栈来保存遍历到的但是还没有访问其右子树元素的结点;
代码:
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> vals; 14 stack<TreeNode*> nodes; 15 TreeNode* node = root; 16 17 while (node != NULL || !nodes.empty()) { 18 while (node) { 19 nodes.push(node); 20 node = node->left; 21 } 22 23 node = nodes.top(); 24 nodes.pop(); 25 vals.push_back(node->val); 26 node = node->right; 27 } 28 29 return vals; 30 } 31 };
时间: 2024-10-05 06:54:41