LeetCode算法题94:二叉树的中序遍历(Binary Tree Inorder Traversal)

技术交流可以加:
本人微信:xcg852390212
本人qq:852390212
学习交流qq群1(已满): 962535112
学习交流qq群2: 780902027

二叉树的中序遍历

LeetCode中文

LeetCode英文

给定一个二叉树,返回它的 中序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

解答

方法1:递归

C++代码

/**
 * 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:
    void recursion(TreeNode* root,vector& res)
    {
        if(!root) return;
        
        recursion(root->left,res);
        res.push_back(root->val);
        recursion(root->right,res);
    }
    
    vector inorderTraversal(TreeNode* root) {
        vector res;
        recursion(root,res);
        
        return res;
    }
};

Python代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def recursion(self,root):
        if root is None:
            return
        self.recursion(root.left)
        self.lt.append(root.val)
        self.recursion(root.right)
        
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        self.lt = []
        self.recursion(root)
        return self.lt

方法2:迭代法(利用栈实现)

(1)树先一直向左走到叶节点并将沿途的结点入栈 ;

(2)然后向右走一步,重复第一步操作。

C++代码

/**
 * 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 inorderTraversal(TreeNode* root) {
        vector res;
        stack sta;
        
        TreeNode* head = root;
        while(head || !sta.empty())
        {
            while(head)
            {
                sta.push(head);
                head = head->left;
            }
            
            head = sta.top();
            res.push_back(head->val);
            sta.pop();
            
            head = head->right;
        }
        
        return res;
    }
};

Python代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        sta,res = [],[]
        head = root
        while head or len(sta) > 0:
            while head:
                sta.append(head)
                head = head.left
            head = sta.pop()
            res.append(head.val)
            head = head.right
        return res
            

你可能感兴趣的:(算法题总结,LeetCode)