zoukankan      html  css  js  c++  java
  • 144.Binary Tree Preorder Traversal---二叉树先序、中序非递归遍历

    题目链接

    题目大意:返回二叉树的先序遍历list。中序见94,后序见145。

    法一:普通递归遍历,只是这里多了一个list数组,所以分成了两个函数。代码如下(耗时1ms):

     1     public List<Integer> preorderTraversal(TreeNode root) {
     2         List<Integer> list = new ArrayList<Integer>();
     3         list = dfs(root, list);
     4         return list;
     5     }
     6     public static List<Integer> dfs(TreeNode root, List<Integer> list) {
     7         if(root == null) {
     8             return list;
     9         }
    10         else {
    11             list.add(root.val);
    12             list = dfs(root.left, list);
    13             list = dfs(root.right, list);
    14             return list;
    15         }
    16     }
    View Code

    法二(借鉴):先序非递归。代码如下(耗时1ms):

     1     public List<Integer> preorderTraversal(TreeNode root) {
     2         Stack<TreeNode> stack = new Stack<TreeNode>();
     3         TreeNode tmp = root;
     4         List<Integer> list = new ArrayList<Integer>();
     5         while(tmp != null || !stack.isEmpty()) {
     6             //将所有左孩子压栈,直到没有左孩子,并且由于是先序遍历,所以在压左孩子的时候就放入结果list中
     7             while(tmp != null) {
     8                 list.add(tmp.val);
     9                 stack.push(tmp);
    10                 tmp = tmp.left;
    11             }
    12             //如果左孩子压完了,就访问右孩子
    13             if(!stack.isEmpty()) {
    14                 tmp = stack.pop();
    15                 tmp = tmp.right;
    16             }
    17         }
    18         return list;
    19     }
    View Code

    中序非递归

     1     public List<Integer> inorderTraversal(TreeNode root) {
     2         List<Integer> list = new ArrayList<Integer>();
     3         Stack<TreeNode> stack = new Stack<TreeNode>();
     4         TreeNode tmp = root;
     5         while(tmp != null || !stack.isEmpty()) {
     6             while(tmp != null) {
     7                 stack.push(tmp);
     8                 tmp = tmp.left;
     9             }
    10             //与先序不同的是,在弹出时放入结果list
    11             if(!stack.isEmpty()) {
    12                 tmp = stack.pop();
    13                 list.add(tmp.val);
    14                 tmp = tmp.right;
    15             }
    16         }
    17         return list;
    18     }
    View Code
  • 相关阅读:
    2019-1-17 水晶报表自动补空行及格线(无分组版)
    通过ssh证书远程登录
    kali linux下不能以root权限运行vlc的解决办法
    SSH服务:packet_write_wait: Connection to 67.218.143.160 port 22: Broken pipe错误处理
    python系列--函数--递归函数
    python虚拟环境安装pyqt5
    docker API接口service update错误记录 error while removing network:…
    docker service create api参数
    docker api参数文档
    docker 集群
  • 原文地址:https://www.cnblogs.com/cing/p/7797389.html
Copyright © 2011-2022 走看看