zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    网页瀑布流收集
    Docker
    CI/CD/Jenkins
    ckplayer获取播放时长一
    aliplay获取播放时长
    06 intent flag三种属性
    06 Activity隐式跳转
    06 Activity显示跳转
    06 Activity的启动模式 Intent的七大属性的总结
    06 Activity OnNewIntent方法
  • 原文地址:https://www.cnblogs.com/zle1992/p/8342423.html
Copyright © 2011-2022 走看看