leetcode94(二叉樹的中序遍歷)

二叉樹的中序遍歷

在這裏插入圖片描述

/**
 * 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);
    }
};

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

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

*/python 
class Solution:
    def inorderTraversal(self,root):
        res = []
        def helper(root):
            if not root:
                return 
            helper(root.left)
            res.append(root.val)
            helper(root.right)
        helper(root)
        return res
*/
class Solution:
    def inorderTraversal(self,root):
        res = []
        if not root:
            return res
        stack = []
        cur = root
        while stack or cur:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            res.append(cur.val)
            cur = cur.right
        return res
        
*/
class Solution:
    def inorderTraversal(self,root):
        WHITE, GRAY = 0,1
        res = []
        stack = [(WHITE,root)]
        while stack:
            color,node = stack.pop()
            if node is None: continue
            if color == WHITE:
                stack.append((WHITE,node.right))
                stack.append((GRAY,node))
                stack.append((WHITE,node.left))
            else:
                res.append(node.val)
        return res
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章