• 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].

    递归:

     1 class Solution {
     2     List<Integer> res = new ArrayList<Integer>(); 
     3     public List<Integer> inorderTraversal(TreeNode root) {
     4           help(root);
     5         return res;
     6     }
     7     private void help(TreeNode root){
     8         if(root==null) return ;
     9         if(root.left!=null)
    10             help(root.left);
    11         
    12         res.add(root.val);
    13         
    14         if(root.right!=null)
    15             help(root.right);
    16     }
    17 }

    非递归:

    终极版:

     1 class Solution {
     2     public List<Integer> inorderTraversal(TreeNode root) {
     3         Stack<TreeNode> s = new Stack<TreeNode>();
     4         List<Integer> res = new ArrayList<Integer>();
     5         while(root!=null||!s.isEmpty()){
     6             while(root!=null){
     7                 s.push(root);
     8                 root=root.left;
     9             }
    10             if(!s.isEmpty()){
    11                 root = s.pop();
    12                 res.add(root.val);
    13                 root = root.right;
    14             }
    15         }
    16         return res;
    17     }
    18 }

    利用辅助桟

     1 class Solution {
     2     
     3     public List<Integer> inorderTraversal(TreeNode root) {
     4         List<Integer> res = new ArrayList<Integer>(); 
     5         Stack<TreeNode> stack = new Stack<TreeNode>();
     6         TreeNode cur = root;
     7         while(cur!=null ||!stack.isEmpty()){
     8             while(cur!=null){
     9                 stack.push(cur);
    10                 cur =cur.left;
    11             }
    12             cur = stack.pop();
    13             res.add(cur.val);
    14             cur =cur.right;
    15         }
    16         return res;
    17     }
    18    
    19 }
  • 相关阅读:
    (转) 应用系统性能监控(二) Pinpoint 使用
    随机滚动名字和试题 单击暂停----给媳妇儿写的爱心小应用
    最短路径问题 java
    数字全排列 java深度优先搜索
    “接竹竿”纸牌游戏 java实现运算结果
    插入排序 java代码
    选择排序 java代码
    快速排序java代码
    1. Django的安装及配置
    python3.x,pycharm的安装
  • 原文地址:https://www.cnblogs.com/zle1992/p/8342423.html
Copyright © 2020-2023  润新知