Binary Tree Preorder Traversal

2016-11-26  本文已影响0人  无为无悔

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



import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {
    public List<Integer> inorderTraverse(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null)
            return result;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        while(p != null || !stack.isEmpty()) {
            if(p != null) {
                stack.push(p);
                result.add(p.val);
                p = p.left;
            }
            else {
                p = stack.pop();
                p = p.right;
            }
        }
        return result;
    }
}

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

// 解法2, 深度优先搜索DFS的思想
public class Solution1 {
    public static List<Integer> preorderTraverse(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null)
            return result;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode p = stack.pop();
            result.add(p.val);
            if(p.right != null) stack.push(p.right);
            if(p.left != null)  stack.push(p.left);
        }
        return result;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读