zoukankan      html  css  js  c++  java
  • Leetcode 94. Binary Tree Inorder Traversal (中序遍历二叉树)

    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(迭代)?

    思路:

    解法一:用递归方法很简单,

    (1)如果root为空,则返回NULL;

    (2)如果root->left != NULL,则返回左子树的中序遍历元素;

    (3)如果root->right != NULL, 则返回右子树的中序遍历元素;

    (4)最后,将左子树的中序遍历元素放入容器,root->val放入容器,再将右子树的中序遍历元素放入容器;

    (5)返回容器;

     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> v, v1, v2;
    14         int i;
    15         if(root == NULL)
    16            return v;
    17         if(root->left != NULL)
    18             v1 = inorderTraversal(root->left);
    19         if(root->right != NULL)
    20             v2 = inorderTraversal(root->right);
    21         for(i = 0; i < v1.size(); i++)
    22             v.push_back(v1[i]);
    23         v.push_back(root->val);
    24         for(i = 0; i < v2.size(); i++)
    25             v.push_back(v2[i]);
    26         return v;
    27     }

    解法二:非递归中序遍历二叉树,要定义一个栈(stack)

     1 class Solution {
     2 public:
     3     vector<int> inorderTraversal(TreeNode* root) {
     4         vector<int> v;
     5         stack<TreeNode*> node_stack;
     6         TreeNode* pNode = root;
     7         while((pNode != NULL) || !node_stack.empty()){
     8             //节点不为空,加入栈中,并访问节点左子树
     9             if(pNode != NULL){
    10                 node_stack.push(pNode);
    11                 pNode = pNode->left;
    12             }
    13             else{
    14                 //节点为空,从栈中弹出一个节点,访问这个节点,
    15                 pNode = node_stack.top();
    16                 node_stack.pop();
    17                 v.push_back(pNode->val);
    18                 //访问节点右子树
    19                 pNode = pNode->right;
    20             }
    21         }
    22         return v;
    23     }
    24 };
  • 相关阅读:
    Python实现决策树ID3算法
    ML——决策树模型
    Linux下用matplotlib画决策树
    RedHat7.2安装matplotlib——之Python.h:没有那个文件或目录
    没想到这么简单——滚雪球
    pyspark中使用累加器Accumulator统计指标
    pscp多线程传输文件
    [笔记] 使用numpy手写k-means算法
    [LeetCode in Python] 309 (M) best time to buy and sell stock with cooldown 最佳买卖股票时机含冷冻期
    [LeetCode in Python] 75 (M) sort colors 颜色分类
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5723247.html
Copyright © 2011-2022 走看看