LeetCode--二叉树1--树的遍历

一 深度遍历

  • 深度遍历里面由 三种遍历方式,两种实现方法。都要熟练掌握。
  • 值得注意的是,当你删除树中的节点时,删除过程将按照后序遍历的顺序进行。
  • 也就是说,当你删除一个节点时,你将首先删除它的左节点和它的右边的节点,然后再删除节点本身。

Note:后序遍历在表达式上的应用

① 用递归的方式遍历二叉树

Note:

递归的实现方式里,函数的返回值需要为void类型,否则没法进行。

所以我们需要设定一个help函数来完成递归。

后序遍历
/**
* 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> postorderTraversal(TreeNode* root ) {
       vector<int> nodes;
       helper( root, nodes);
       return nodes;
 
  }
   void helper(TreeNode *pnode , vector<int> &node_ids)
  {
       if( pnode == NULL)
      {
           std::cout  << " The tree is null ! " << std::endl;
      }
       else
      {
           if(pnode != NULL)
               helper(pnode->left,node_ids);
           if(pnode != NULL)
               helper(pnode->right,node_ids);
           node_ids.push_back(pnode->val);
      }  
  }
};
前序遍历
/**
* 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> preorderTraversal(TreeNode* root ) {
       vector<int> nodes;
       helper( root, nodes);
       return nodes;
 
  }
   void helper(TreeNode *pnode , vector<int> &node_ids)
  {
       if( pnode == NULL)
      {
           std::cout  << " The tree is null ! " << std::endl;
      }
       else
      {
           node_ids.push_back(pnode->val);
           if(pnode != NULL)
               helper(pnode->left,node_ids);
           if(pnode != NULL)
               helper(pnode->right,node_ids);
      }  
  }
};
中序遍历
/**
* 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> nodes;
       helper( root, nodes);
       return nodes;
 
  }
   void helper(TreeNode *pnode , vector<int> &node_ids)
  {
       if( pnode == NULL)
      {
           std::cout  << " The tree is null ! " << std::endl;
      }
       else
      {
           if(pnode != NULL)
               helper(pnode->left,node_ids);
           node_ids.push_back(pnode->val);
           if(pnode != NULL)
               helper(pnode->right,node_ids);
      }  
  }
};

② 用非递归的方式遍历二叉树

用递归方式实现的问题都可以用非递归方法实现。

递归的本质就是利用函数栈来保存信息。

用自己申请的数据结构来代替函数栈,可以实现同样的功能。

①使用栈实现前序遍历:
  1. 申请一个栈stack,头结点入栈。
  2. 栈顶元素出栈,出栈元素的右节点和左节点依次入栈。
  3. 重复第二步,直到栈为空
/**
* 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> preorderTraversal(TreeNode* root) {
       vector<int> orders;
       stack<TreeNode*> nodes;
       TreeNode* tmp;
       
       if (root == NULL)
      {
           std::cerr << "The Tree is NULL !!!" << std::endl;
      }
       else
      {
           nodes.push(root);
           while(nodes.empty()==0)
          {
               tmp =  nodes.top();
               nodes.pop();
               orders.push_back(tmp->val);
               if(tmp->right!=NULL)
                   nodes.push(tmp->right);
               if(tmp->left!= NULL)
                   nodes.push(tmp->left);
          }        
      }
       return orders;
  }
};
②使用栈实现中序遍历:
  1. 申请一个新的栈stack,定义一个变量 cur = root 节点
  2. cur入栈
  3. 令 cur = cur.left,重复步骤2,直到cur = NULL
  4. stack.pop(); 出栈的节点记为 node,输出 node.val
  5. 令 cur = node.right 重复2,3
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> inorder;
TreeNode* cur = root;
if(root != NULL)
{
stack<TreeNode*> kk ;
while( !kk.empty() || cur != NULL)
{
if(cur != NULL)
{
kk.push(cur);
cur = cur->left;
}
else
{
cur = kk.top();
kk.pop();
inorder.push_back(cur->val);
cur = cur->right;
}
}
}
return inorder;
}
};

二 层次遍历

其实就是逐层遍历树的结构

广度优先搜索一种广泛运用在树或图这类数据结构中,遍历或搜索的算法。

该算法从一个根节点开始,首先访问节点本身。

然后遍历它的相邻节点,其次遍历它的二级邻节点、三级邻节点,以此类推。

当我们在树中进行广度优先搜索时,我们访问的节点的顺序是按照层序遍历顺序的。

实现有两种模板
  1. 以层为单位输出
  2. 以节点为单位输出
按层为单位过程
  1. 头节点入队
  2. 如果队列不为空,取到队列的元素个数,得知上一个循环加入队列的元素个数,也就是上一层的元素个数。for循环令上一层的元素出队列,并把其左右子树入队。

核心:

就是 while 循环里面套一个 for 循环。

.

.

.

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}; class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(root == NULL)
return ans;
queue<TreeNode*> q;
q.push(root);
while( !q.empty() )
{
int num = q.size();
vector<int> cur;
for (int i = 0 ; i < num; i++)
{
TreeNode* pnode = q.front();
q.pop();
if (pnode->left != NULL)
q.push(pnode->left);
if (pnode->right != NULL)
q.push(pnode->right);
cur.push_back(pnode->val);
}
ans.push_back(cur);
}
return ans;
}
};

LeetCode--二叉树1--树的遍历的更多相关文章

  1. [LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历

    Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary tre ...

  2. LeetCode总结 -- 树的遍历篇

    遍历树的数据结构中最常见的操作. 能够说大部分关于树的题目都是环绕遍历进行变体来解决的. 一般来说面试中遇到树的题目是用递归来解决的, 只是假设直接考察遍历. 那么一般递归的解法就过于简单了. 面试官 ...

  3. LeetCode 107 Binary Tree Level Order Traversal II(二叉树的层级顺序遍历2)(*)

    翻译 给定一个二叉树,返回从下往上遍历经过的每一个节点的值. 从左往右,从叶子到节点. 比如: 给定的二叉树是 {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 返回它从下 ...

  4. [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  5. Leetcode:1008. 先序遍历构造二叉树

    Leetcode:1008. 先序遍历构造二叉树 Leetcode:1008. 先序遍历构造二叉树 思路 既然给了一个遍历结果让我们建树,那就是要需要前序中序建树咯~ 题目给的树是一颗BST树,说明中 ...

  6. [LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历

    Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary ...

  7. [LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  8. (PAT)L2-006 树的遍历 (二叉树构建)

    题目链接:https://www.patest.cn/contests/gplt/L2-006 给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列.这里假设键值都是互不相等的正整数. 输入格 ...

  9. L2-006 树的遍历 (25 分) (根据后序遍历与中序遍历建二叉树)

    题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805069361299456 L2-006 树的遍历 (25 分 ...

  10. LeetCode(94):二叉树的中序遍历

    Medium! 题目描述: 给定一个二叉树,返回它的中序 遍历. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗 ...

随机推荐

  1. python处理nii格式文件

    网上已经有很多代码了,但是注释的都不全,看起来很费解,我自己加了一些注释,重新发出来,尽可能的通俗易懂 读取前需要先安装库 pip install nibabel pip install matplo ...

  2. 新年在家学java之基础篇--类&方法

    面向对象 面向对象OOP,面向过程POP 面向对象三大特征 封装 继承 多态 类 类由属性(对应类中的成员变量)和行为(成员方法)来构成 类的成员变量可以先声明,不用初始化,有默认值 方法名称如果多个 ...

  3. Spring Boot中@Async的作用

    在Spring中,@Async这个注解用于标记的异步的方法.方法上一旦标记了这个方法,当其它线程调用这个方法时,就会开启一个新的线程去异步处理业务逻辑. 此注解的使用说明: 1.此注解可以用在方法上, ...

  4. LGOJ1290 欧几里德的游戏

    题目链接 P1290 and UVA10368 (双倍经验[虽然标签差距很有趣]) 题目大意 给定两个数\(n\)和\(m\),每次操作可以用较大数减去较小数的正整数倍,不可以减成负数. 先获得一个\ ...

  5. php7 安装mongodb扩展

    下载 mongodb-1.6.0.tgz   wget https://pecl.php.net/get/mongodb-1.6.0.tgz  版本太低的话有些语法不一样,起码1.5以上吧 进入 mo ...

  6. Java && Python 算法面试常用类以及方法总结

    数据结构 逻辑结构上: 包括集合,线性结构,非线性结构. 存储结构: 顺序存储,链式存储,索引存储,散列存储. Java 常见数据结构 大专栏  Java && Python 算法面试 ...

  7. NIO与IO

    待续... 该文章部分摘自:http://tutorials.jenkov.com/java-nio/index.html 一.I/O简介 I/O(英语:Input/Output),即输入/输出, 指 ...

  8. python-django-redis拒绝连接问题解决_20191121

    今天安装fastdfs的时候,发现最好固定虚拟机的ip, 固定了ip之后,发现使用Windows中的pycharm连接redis的时候,总是拒绝连接,找了很多的办法都不行,有点慌, 但是不能慌,现在要 ...

  9. axious设置携带cookie同时允许跨域的问题

    axious设置携带cookie同时允许跨域的问题

  10. POJ-1811-Prime Test(pollard_rho模板,快速找最小素因子)

    题目传送门 sol:Pollard_Rho的模板题,刚看了Pollard_Rho和Miller_Rabin很多原理性的东西看不懂,只是记住了结论勉强能敲代码. Pollard_Rho #include ...