您的位置:首页 > 其它

leetcode 94. Binary Tree Inorder Traversal-中序遍历|递归|非递归

2016-05-23 16:03 411 查看
原题链接:94. Binary Tree Inorder Traversal
【思路-Java、Python】

非递归实现用到了栈,以[1,2,3,4,5,null,6]为例,下图模拟了这个过程



public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while(true) {
while (root != null) {
stack.add(root);
root = root.left;
}
if (stack.isEmpty()) break;
root = stack.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}
67 / 67 test
cases passed. Runtime: 3
ms Your runtime beats 0.60% of javasubmissions.

class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = []
res = []
while 1 :
while root :
stack.append(root)
root = root.left
if not stack : break
root = stack.pop()
res.append(root.val)
root = root.right
return res
67 / 67 test
cases passed. Runtime: 52
ms Your runtime beats 9.94% of pythonsubmissions.

【补充非递归实现-Java、Python】

public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
dfs(root, res);
return res;
}
public void dfs(TreeNode root, List<Integer> res) {
if (root == null) return;
dfs(root.left, res);
res.add(root.val);
dfs(root.right, res);
}
}


67 / 67 test
cases passed. Runtime: 1
ms Your runtime beats 62.04% of javasubmissions.

class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def dfs(root,res) :
if not root : return
dfs(root.left, res)
res.append(root.val)
dfs(root.right, res)
dfs(root,res)
return res
67 / 67 test
cases passed Runtime: 56
ms Your runtime beats 5.74% of pythonsubmissions.

挑战更多:


leetcode 230. Kth Smallest Element in a BST-递归|非递归

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: