LeetCode brushing notes _94. In-order traversal of binary tree

The topic is from LeetCode

94. In-order traversal of binary tree

Other solutions or source code can be accessed: tongji4m3

description

Given a binary tree, return its middle order traversal.

Example:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

Ideas

Iteration: Using the stack method, the idea is similar to recursion. First go to the left to the end, if you can't go, go back one square and add the current element. Then continue to view the right node of the current element. After finishing the node, go back one grid. Until the root node is finished.

detail

Code

//递归
public List<Integer> inorderTraversal(TreeNode root)
{
    
    
    List<Integer> result = new LinkedList<>();
    recursive(root, result);
    return result;
}

private void recursive(TreeNode node, List<Integer> result)
{
    
    
    if(node==null)
    {
    
    
        return;
    }
    recursive(node.left,result);
    result.add(node.val);
    recursive(node.right,result);
}
//迭代
public List<Integer> inorderTraversal(TreeNode root)
{
    
    
    List<Integer> result = new LinkedList<>();
    Stack<TreeNode> stack = new Stack<>();
    TreeNode current = root;
    
    //current!=null 代表了还存在右节点
    //!stack.isEmpty() 代表了存在父节点
    //当然开始时只是看根节点
    while(current!=null || !stack.isEmpty())
    {
    
    
        while(current!=null)
        {
    
    
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        result.add(current.val);
        current = current.right;
    }
    return result;
}

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108414622