zoukankan      html  css  js  c++  java
  • LeetCode:Binary Tree Preorder Traversal(二叉树的先序遍历)

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

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

       1
        
         2
        /
       3
    

    return [1,2,3].

    解法一:用栈实现(递归本质)

     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> preorderTraversal(TreeNode* root) {
    13         vector<int> result;
    14         stack<TreeNode *> node_stack;
    15         if(root!=NULL)
    16             node_stack.push(root);
    17         TreeNode *node;
    18         
    19         while(!node_stack.empty())
    20         {   
    21             node=node_stack.top();
    22             result.push_back(node->val);
    23             node_stack.pop();
    24             
    25             if(node->right!=NULL) node_stack.push(node->right);
    26             if(node->left!=NULL) node_stack.push(node->left);
    27         }
    28         
    29         return result;       
    30         
    31     }
    32 };

     解法二:递归方式

     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> preorderTraversal(TreeNode* root) {
    13         vector<int> result;
    14         preorder(root,result);
    15         return result;
    16         
    17         
    18     }
    19     void preorder(TreeNode *node,vector<int> &result)
    20     {   
    21         if(node!=NULL)
    22         {
    23             result.push_back(node->val);
    24             preorder(node->left,result);
    25             preorder(node->right,result);
    26         }
    27         
    28     }
    29 };

     解法三:morris遍历方式 有待更新。

  • 相关阅读:
    自定义注解 使用反射实现切面编程
    JPA学习(基于hibernate)
    MySql数据库优化可以从哪几个方面进行?
    mybatis注解开发-动态SQL
    mybatis注解开发
    mybatis动态sql
    Java8新特性之forEach遍历
    mybatis一对多映射
    CentOS7.* 查询开机启动项
    CentOS7 升级openssh到openssh-8.0p1版本
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4723651.html
Copyright © 2011-2022 走看看