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;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Xiouzai_/article/details/82873226
今日推荐