1. 程式人生 > >LeetCode94. 二叉樹的中序遍歷(Binary tree Inorder Traversal)

LeetCode94. 二叉樹的中序遍歷(Binary tree Inorder Traversal)

題目描述

給定一個二叉樹,返回它的中序 遍歷。

示例:

輸入: [1,null,2,3]
   1
    \
     2
    /
   3
輸出: [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> res; inorder(root, res); return res; } void inorder(TreeNode *root, vector<int> &res) { if (!root) return; if (root->left) inorder(root->
left, res); res.push_back(root->val); if (root->right) inorder(root->right, res); } };

非遞迴思路:

需要用棧來做,思路是從根節點開始,先將根節點壓入棧,然後再將其所有左子結點壓入棧,然後取出棧頂節點,儲存節點值,再將當前指標移到其右子節點上,若存在右子節點,則在下次迴圈時又可將其所有左子結點壓入棧中。這樣就保證了訪問順序為左-根-右。

非遞迴程式碼:

/**
 * 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> res; stack<TreeNode*> s; TreeNode *p=root; while(p||!s.empty()){ while(p){ s.push(p); p=p->left; } p=s.top(); s.pop(); res.push_back(p->val); p=p->right; } return res; } };