LeetCode算法题94:二叉树的中序遍历解析

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

示例:

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

输出: [1,3,2]

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

递归法直接从左向右添加元素即可,C++程序使用递归法。迭代法用到了栈,先从根结点开始保存所有的左节点到栈中,然后以此从栈顶推出节点,然后保存节点值,将节点再指向其右节点进行循环。

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

python3源代码:

# 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):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        s = []
        p = root
        while p or len(s)!=0:
            while p:
                s.append(p)
                p = p.left
            p = s.pop()
            res.append(p.val)
            p = p.right
        return res

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/87854910