1. 程式人生 > >LeetCode Week 4

LeetCode Week 4

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

在這裡插入圖片描述
Follow up: Recursive solution is trivial, could you do it iteratively?

solutions:

本題意是要求不使用遞迴的方法,而是使用迭代的方法對二叉樹進行中序遍歷,並最終儲存到vector容器中輸出。

根據中序遍歷的順序,對於任一結點,優先訪問其左孩子,而左孩子結點又可以看做一根結點,然後繼續訪問其左孩子結點,直到遇到左孩子結點為空的結點才進行訪問,然後按相同的規則訪問其右子樹。因此其處理過程如下:

對於任一結點P,

1)若其左孩子不為空,則將P入棧並將P的左孩子置為當前的P,然後對當前結點P再進行相同的處理;

2)若其左孩子為空,則取棧頂元素並進行出棧操作,訪問該棧頂結點,然後將當前的P置為棧頂結點的右孩子;

3)直到P為NULL並且棧為空則遍歷結束。

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

在這裡插入圖片描述