leetcode笔记(二)94. Binary Tree Inorder Traversal
- 题目描述 (原题目链接)
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].
- 解题思路
这道题目是关于二叉树中序遍历的迭代实现。之前就总结过二叉树的非递归实现。可是做题的时候太久没刷题,就断路了。所以重新思考了一种解法。
主要想法是:用一个标记位标记是否需要遍历当前节点的左孩子。
具体想法:
-
- 对于一个节点,如果需要遍历过左孩子,就先遍历左孩子,并更新当前节点。
- 接着输出当前节点,弹出当前节点。
- 如果当前节点有右孩子,就添加右孩子,标记需要遍历其左孩子;否则标记不需要遍历左孩子。
结合这个思路,编码实现如下:
/** * 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<int> results; if(root == NULL) return results; stack<TreeNode*> nodes; nodes.push(root); TreeNode* curr; int shouldFindLeft = 1; while(!nodes.empty()) { curr = nodes.top(); // add all left nodes if(shouldFindLeft == 1) { while(curr->left != NULL) { nodes.push(curr->left); curr = curr -> left; } } // print curr node results.push_back(curr->val); nodes.pop(); // add its right child if(curr->right != NULL) { nodes.push(curr->right); shouldFindLeft = 1; } else { shouldFindLeft = 0; } } return results; } };

浙公网安备 33010602011771号