leetcode No94. Binary Tree Inorder Traversal

    xiaoxiao2025-02-08  14

    Question:

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

    For example: Given binary tree [1,null,2,3],

    1 \ 2 / 3

    return [1,3,2].

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

    中序遍历,左-根-右

    Algorithm:

    递归,和非递归两种方法,见程序

    Accepted Code:

    法一:递归     相当慢 /** * 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> res; vector<int> inorderTraversal(TreeNode* root) { if(root!=NULL) { inorderTraversal(root->left); res.push_back(root->val); inorderTraversal(root->right); } return res; } }; 法二:非递归,用栈实现 /** * 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; stack<TreeNode*> stack; TreeNode* pNode=root; while(pNode||!stack.empty()) { if(pNode!=NULL) //节点不为空,加入栈中,并访问节点左子树 { stack.push(pNode); pNode=pNode->left; } else { pNode=stack.top(); //节点为空,从栈中弹出一个节点,访问这个节点 stack.pop(); res.push_back(pNode->val); pNode=pNode->right; //访问节点右子树 } } return res; } };
    转载请注明原文地址: https://ju.6miu.com/read-1296206.html
    最新回复(0)