首页 > 其他 > 详细

Leetcode: Binary Tree Inorder Transversal

时间:2014-09-15 09:54:08      阅读:194      评论:0      收藏:0      [点我收藏+]
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?

难度:50

recursive 方法:

 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 List<Integer> inorderTraversal(TreeNode root) {
12         ArrayList<Integer> res = new ArrayList<Integer>();
13         if (root == null) return res;
14         helper(root, res);
15         return res;
16     }
17     
18     public void helper(TreeNode root, ArrayList<Integer> res) {
19         if (root == null) {
20             return;
21         }
22         if (root.left != null) {
23             helper(root.left, res);
24         }
25         res.add(root.val);
26         if (root.right != null) {
27             helper(root.right, res);
28         }
29     }
30 }

Iterative method: 参考了一下网上的思路,其实就是用一个栈来模拟递归的过程。所以算法时间复杂度也是O(n),空间复杂度是栈的大小O(logn)。

 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 List<Integer> inorderTraversal(TreeNode root) {
12         ArrayList<Integer> result = new ArrayList<Integer>();
13         if (root == null) return result;
14         LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
15         while (root != null || !stack.isEmpty()) {
16             if (root != null) {
17                 stack.push(root);
18                 root = root.left;
19             }
20             else {
21                 root = stack.pop();
22                 result.add(root.val);
23                 root = root.right;
24             }
25         }
26         return result;
27     }
28 }

 

Leetcode: Binary Tree Inorder Transversal

原文:http://www.cnblogs.com/EdwardLiu/p/3972139.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!