zoukankan      html  css  js  c++  java
  • leecode第九十四题(二叉树的中序遍历)

    /**
     * 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> result;
            if(root==NULL)//判断边界
                return result;
            
            stack<TreeNode*> sta;//用栈结构,首先把根节点及所有左子节点打进去
            TreeNode* head=root;
            while(head!=NULL)
            {
                sta.push(head);
                head=head->left;
            }
            
            while(!(sta.empty()&&head->right==NULL))//除非栈为空且右孩子为NULL
            {
                head=sta.top();//否则就弹出栈的top
                sta.pop();
                
                result.push_back(head->val);//记录其值
                
                if(head->right!=NULL)//如果top有右孩子
                {
                    head=head->right;//把右孩子及其所有左孩子节点打进栈
                    while(head!=NULL)
                    {
                        sta.push(head);
                        head=head->left;
                    }
                }
            }
            return result;
        }
    };

    分析:

    使用栈结构实现迭代。

    https://www.cnblogs.com/qjmnong/p/9135386.html

  • 相关阅读:
    64_q2
    64_q1
    64_p10
    64_p9
    64_p8
    64_p7
    64_p6
    64_p5
    64_p4
    64_p3
  • 原文地址:https://www.cnblogs.com/CJT-blog/p/11213841.html
Copyright © 2011-2022 走看看