Binary Tree Inorder Traversal--leetcode,inordertraversal

來源:互聯網
上載者:User

Binary Tree Inorder Traversal--leetcode,inordertraversal

原題連結:https://oj.leetcode.com/problems/binary-tree-inorder-traversal/

題目大意:中序遍曆二叉樹

解題思路:中序遍曆二叉樹,中序遍曆二叉樹的左子樹,訪問根結點,中序遍曆二叉樹的右子樹。非遞迴實現時,用一個棧類比遍曆過程即可。因為需要先遍曆左子樹,所以每個結點先入棧,出棧時訪問。

vector<int> inorderTraversal(TreeNode *root) {        vector<int> ret;        if(!root)            return ret;        stack<TreeNode*> s;        while(root||!s.empty())        {            if(!root)            {root=s.top();ret.push_back(root->val);s.pop();root=root->right;            }else{s.push(root);root=root->left;}        }

複雜度分析:時間複雜度為O(N),因為每個結點僅遍曆一次。空間複雜度為O(lgN),為棧的最大長度,即樹深。

中序遍曆和先許遍曆一樣需要熟練掌握,bug-free哦!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.