LeetCode之94. Binary Tree Inorder Traversal

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

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

自己的代码:

方法一:递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public static List<Integer> inorderTraversal(TreeNode root) {
		if(root == null){
			return Collections.emptyList();
		}
		List<Integer> result = new ArrayList<>();
		helper(result,root);
		return result;
	}
	
	public static void helper(List<Integer> result,TreeNode root) {
		if(root == null) {  // 这个if判断不能少,否则会有空指针异常
			return;
		}
		helper(result,root.left);
		result.add(root.val);
		helper(result,root.right);
	}
}

方法二:用栈实现迭代中序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public static List<Integer> inorderTraversal(TreeNode root) {
		List<Integer> result = new ArrayList<>();
		Stack<TreeNode> stack = new Stack<>();
		TreeNode cur = root;
		
		while(cur != null || !stack.isEmpty()) {
			if(cur != null) {
				stack.add(cur);
				cur = cur.left; // 一直向左走,走到走不动为止
			}else {
				cur = stack.pop();
				result.add(cur.val);
				
				cur = cur.right; // 向右走一步
			}
		}
		
		return result;
	}
}

Python:

# recursively:递归版本
def inorderTraversal1(self, root):
    res = []
    self.helper(root, res)
    return res
    
def helper(self, root, res):
    if root:
        self.helper(root.left, res)
        res.append(root.val)
        self.helper(root.right, res)
 
# iteratively:迭代版本    
def inorderTraversal(self, root):
    res, stack = [], []
    while True:
        while root:
            stack.append(root)
            root = root.left
        if not stack:                # 这句还不是特别理解????
            return res
        node = stack.pop()
        res.append(node.val)
        root = node.right

自己的代码:

扫描二维码关注公众号,回复: 5559696 查看本文章
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None



class Solution(object):
    def inorderTraversal(self, root):
        res, stack = [], []
        cur = root
        while cur or len(stack)>0:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                res.append(cur.val)
                cur = cur.right

        return res # 这个在while循环代码块之外

            小结:

            1)因为stack = [ ] ,实质就是一个list列表, 列表没有isEmpty(),只能通过len(stack)判断栈中元素个数;

            2)列表有pop()和append()函数

            3)java中的while(cur != null) 等价于Python中的 “ while cur: ”

猜你喜欢

转载自blog.csdn.net/iNiBuBian/article/details/87986114
今日推荐