leetcode -- Binary Tree Inorder Traversal

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

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

   1
    \
     2
    /
   3

 return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

Recursive Version

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public ArrayList<Integer> inorderTraversal(TreeNode root) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         ArrayList<Integer> result = new ArrayList<Integer>();
15         if(root == null){
16             return result;
17         }
18         
19         if(root.left != null){
20             result.addAll(inorderTraversal(root.left));
21         }
22         result.add(root.val);
23         if(root.right != null){
24             result.addAll(inorderTraversal(root.right));
25         }
26         return result;
27     }
28 }

 Iterative Version

 1 public  ArrayList<Integer> inorderTraversal(TreeNode root) {
 2             // Start typing your Java solution below
 3             // DO NOT write main() function
 4             ArrayList<Integer> res = new ArrayList<Integer>();
 5             if(root==null) return res;
 6             
 7             Stack<TreeNode> s = new Stack<TreeNode>();
 8             TreeNode cur = root;
 9             while(!s.isEmpty()||cur!=null){
10                 if(cur!=null){
11                     s.push(cur); 
12                     cur=cur.left;
13                 }else{
14                     cur=s.pop();
15                     res.add(cur.val);
16                     cur=cur.right;
17                 }
18             }
19             return res;
20         }

复杂度:时间O(n),空间O(logn)

Morris 算法见如下链接

http://gongxuns.blogspot.com/2012/12/leetcodebinary-tree-inorder-traversal.html

转载于:https://www.cnblogs.com/feiling/p/3256607.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值