[leetcode] 94. Binary Tree Inorder Traversal

Description

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

分析

  • 递归的方法很简单,注意终止条件就行了。
  • 非递归版本需要用到栈来模拟,先要遍历到树的最左边,用栈记录回溯的路径,对每一个出栈的元素,检测其右分支,把右分支的左节点压入栈中,把出栈的值押入结果集合中,因为出栈的顺序就是中序遍历的顺序。
  • 如果读者是在不明白,还是老样子,手工对着代码模拟一下啦

代码-递归版

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

代码-非递归版

/**
 * Definition for binary tree
 * 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 result;
        if(root==NULL){
            return result;
        }
        stack s1;
        TreeNode *temp=root;
        while(!s1.empty()||temp!=NULL){
            while(temp){
                s1.push(temp);
                temp=temp->left;
            }
            
            if(!s1.empty()){
                temp=s1.top();
                s1.pop();
                result.push_back(temp->val);
                temp=temp->right;
            }
        }
        return result;
    }
};

参考文献

[编程题]binary-tree-inorder-traversal

你可能感兴趣的:(C++,leetcode,leetcode题解)