zoukankan      html  css  js  c++  java
  • 94. Binary Tree Inorder Traversal

    一、题目

      1、审题

      

      2、分析

        给出一个二叉树,中序输出其各节点值。

    二、解答

      1、思路: 

        方法一、

          采用递归

    public List<Integer> inorderTraversal(TreeNode root) {
            
            List<Integer> resultList = new ArrayList<Integer>();
            inOrder(resultList, root);
            return resultList;
        }
        
        private void inOrder(List<Integer> resultList, TreeNode root) {
            
            if(root != null) {
                inOrder(resultList, root.left);
                resultList.add(root.val);
                inOrder(resultList, root.right);
            }
        }

      

      方法二、

        采用一个栈记录节点,根节点先入栈

        ①、访问栈顶节点(未出栈),若有左节点则左节点入栈,且将原栈顶节点 left 赋为空。

        ②、若左节点为空,则站顶出栈,且右节点入栈。

        保持了 左 --> 根 --> 右 的访问顺序。

    public List<Integer> inorderTraversal2(TreeNode root) {
            
            List<Integer> resultList = new ArrayList<Integer>();
            if(root == null)
                return resultList;
            
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.add(root);
    
            while(!stack.isEmpty()) {
                TreeNode node = stack.peek();
                if(node.left != null) {
                    stack.push(node.left);
                    node.left = null;    // 左节点以入栈,则标记为空,否则死循环
                }
                else {
                    resultList.add(stack.pop().val);    // 左节点为 null, 则访问头结点
                    if(node.right != null)    // 插入右节点
                        stack.push(node.right);
                }
            }
            
            return resultList;
        }

       

        方法三、

          将二叉树分成两个分支。

          左分支(包含根节点)、右分支,先左分支入栈到底。在出栈访问,访问时站顶节点出栈后,站顶节点右节点入栈。

    public List<Integer> inorderTraversal3(TreeNode root) {
            
            List<Integer> resultList = new ArrayList<Integer>();
            
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            
            while(cur != null || !stack.isEmpty()) {
                while(cur != null) {    // 添加所有左节点
                    stack.add(cur);
                    cur = cur.left;
                }
                
                cur = stack.pop();    // 访问栈顶节点
                resultList.add(cur.val);
                cur = cur.right;    // 指向栈顶节点右节点
            }
            return resultList;
        }
  • 相关阅读:
    leetcode 29-> Divide Two Integers without using multiplication, division and mod operator
    ros topic 发布一次可能会接收不到数据
    python中的print()、str()和repr()的区别
    python 部分函数
    uiautomatorviewer错误 unable toconnect to adb
    pyqt 不规则形状窗口显示
    appium 计算器demo
    Spring 3.0 注解注入详解
    Spring Autowire自动装配
    restful 学习地址
  • 原文地址:https://www.cnblogs.com/skillking/p/9707260.html
Copyright © 2011-2022 走看看