zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] Binary Tree Inorder Traversal

    题目:

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

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,3,2].

    思路:题中规定用循环代替递归求解,用辅助stack来存储遍历到的节点,如果不为空则入栈,否则出栈赋值,并指向其右节点。

    代码:

    public class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> req = new ArrayList<Integer>();
            
            if(root == null)
                return req;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            
            while(!stack.isEmpty() || root != null){
                if(root != null){
                    stack.push(root);
                    root = root.left;
                }else{
                    TreeNode temp = stack.pop();
                    req.add(temp.val);
                    root = temp.right;       //最重要的一步
                }
                
            }
            
            return req;
        }
    }

    参考链接: http://www.programcreek.com/2012/12/leetcode-solution-of-binary-tree-inorder-traversal-in-java/

  • 相关阅读:
    主函数main
    static关键字
    this关键字
    构造函数
    封装
    匿名对象
    java基础积累
    JAVA相关知识复习
    ORACLE数据库表空间查询
    两个日期的时间差
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4518975.html
Copyright © 2011-2022 走看看