Leetcode 144. Preorder traversal recursive solution and non-recursive solution of binary tree

Leetcode 144. Preorder traversal of binary tree

Title description

Give you the root node root of the binary tree, and return the preorder traversal of its node value.

Example 1:
Insert picture description here

输入:root = [1,null,2,3]
输出:[1,2,3]

Example 2:

输入:root = []
输出:[]

Example 3:

输入:root = [1]
输出:[1]

Example 4:
Insert picture description here

输入:root = [1,2]
输出:[1,2]

Example 5:
Insert picture description here

输入:root = [1,null,2]
输出:[1,2]

prompt:

The number of nodes in the tree is within the range [0, 100]
-100 <= Node.val <= 100

Advanced: The recursive algorithm is very simple, can you do it through an iterative algorithm?
Place.

Solution 1: Recursion

Design a function and then recursively call to achieve traversal

  public List<Integer> preorderTraversal(TreeNode root) {
    
    
        List<Integer> list = new LinkedList<>();
        preorderTraversal(root,list);
        return list;
    }
    public void preorderTraversal(TreeNode root, List<Integer> list) {
    
    
           if (root==null){
    
    
               return;
           }
           list.add(root.val);
           preorderTraversal(root.left,list);
           preorderTraversal(root.right,list);
    }

Solution two: non-recursive

template

The traversal of the binary tree can be thought of based on this template. On this basis, you can always think about it carefully.

while( 栈非空 || p 非空)
{
    
    
if( p 非空)
{
    
    

}
else
{
    
    

}
}

Use the stack to achieve

1. First push the root node onto the stack
2. Perform the following operations in a loop:
pop the top element of
the stack, push the left node of
the top node of the stack, push the child node of the top node of the stack,

Insert picture description here

public class Leetcode144_2 {
    
    
    public List<Integer> preorderTraversal(TreeNode root) {
    
    
        LinkedList<Integer> list = new LinkedList<>();
        if (root==null){
    
    
            return list ;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node=root;
        stack.add(node);
        while(!stack.isEmpty()){
    
    
             node=stack.pop();
             list.add(node.val);
             if (node.right!=null){
    
    
                 stack.add(node.right);
             }
             if (node.left!=null){
    
    
                 stack.add(node.left);
             }
        }
        return list;
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/pjh88/article/details/114677013