zoukankan      html  css  js  c++  java
  • 39.Binary Tree Inorder Traversal(二叉树中序遍历)

    Level:

      Medium

    题目描述:

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

    思路分析:

      实现一棵二叉树的中序遍历,我们可以用简单的递归方法去实现,也可以使用栈去实现,使用第二种方式时,我们沿着根节点先遍历左子树的左孩子,将它们依次压入栈,知道左孩子为空,弹出栈顶节点,这时记录栈顶节点的值,如果栈顶节点的右孩子不为空,压入栈,如果为空,则栈顶元素继续弹出,重复上述操作,就能获得中序遍历的结果。

    代码:

    /**public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int x){
            val=x;
        }
    }*/
    public class Solution{
        public List<Integer> inorderTraversal(TreeNode root){
            List<Integer>res=new ArrayList<>();
            Stack<TreeNode>s=new Stack<>();
            if(root==null)
                return res;
            TreeNode pNode=root;
            while(pNode!=null||!s.isEmpty()){
                if(pNode!=null){
                    s.push(pNode);
                    pNode=pNode.left;
                }else{
                    TreeNode Node=s.pop();
                    res.add(Node.val);
                    pNode=Node.right;
                }
            }
            return res;
        } 
    }
    
  • 相关阅读:
    mac 下 安装 mongodb
    ajax常见的面试问题
    js 数组api
    vue 项目中的坑 在项目中遇到 持续更新ing
    移动端适配问题
    axios API速查表
    移动端常用的 meta设置
    python 首次安装 报错
    在vue项目中使用sass
    SPA单页面应用
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11074902.html
Copyright © 2011-2022 走看看