• 【Leetcode】【Medium】Binary Tree Inorder Traversal


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

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,3,2].

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

    解题思路:

    二叉树中序非递归遍历,使用栈来保存遍历到的但是还没有访问其右子树元素的结点;

    代码:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> inorderTraversal(TreeNode* root) {
    13         vector<int> vals;
    14         stack<TreeNode*> nodes;
    15         TreeNode* node = root;
    16         
    17         while (node != NULL || !nodes.empty()) {
    18             while (node) {
    19                 nodes.push(node);
    20                 node = node->left;
    21             }
    22             
    23             node = nodes.top();
    24             nodes.pop();
    25             vals.push_back(node->val);
    26             node = node->right;
    27         }
    28         
    29         return vals;
    30     }
    31 };
  • 相关阅读:
    Django路由系统
    修改数据库时区问题
    Django框架篇
    前端css
    前端html
    前端初识
    数据库3
    数据库2
    数据库1
    数据库初识
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4521377.html
Copyright © 2020-2023  润新知