preOrder 二叉树先序遍历 144. Binary Tree Preorder Traversal

慢慢练脑子

留意下非递归方法,存stack前先检测下是否为null

1. 来源:

题: leetcode

2. 解法:

2.1 递归

class Solution {
    public List preorderTraversal(TreeNode root) {
        List result = new ArrayList<>();
        helper(root, result);
        
        return result;
    }
    
    private void helper(TreeNode root, List result) {
        
        if(root == null) {
            return;
        }
        
        result.add(root.val);
        helper(root.left, result);
        helper(root.right, result);
        
    }
}

2.1 非递归

class Solution {
    public List preorderTraversal(TreeNode root) {
        
        List result = new ArrayList<>();
        
        Stack nodeStack = new Stack<>();
        if(root == null) {
            return result;
        }
        
        nodeStack.add(root);
        while(!nodeStack.isEmpty()) {
            TreeNode top = nodeStack.pop();
            
            result.add(top.val);
            if(top.right != null) {  // 先push右,再push做
                nodeStack.push(top.right);
            }
            if(top.left != null) {
                nodeStack.push(top.left);
            }
        }
        
        return result;
        
    }
}

你可能感兴趣的:(preOrder 二叉树先序遍历 144. Binary Tree Preorder Traversal)