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

原题链接:94. Binary Tree Inorder Traversal

【思路-Java、Python】

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

leetcode 94. Binary Tree Inorder Traversal-中序遍历|递归|非递归_第1张图片

public class Solution {
    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList();
        Stack stack = new Stack();
        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 inorderTraversal(TreeNode root) {
        List res = new ArrayList();
        dfs(root, res);
        return res;
    }
    public void dfs(TreeNode root, List 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-递归|非递归


你可能感兴趣的:(LeetCode)