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

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

    For example:
    Given binary tree [1,null,2,3],

       1
        
         2
        /
       3
    

    return [1,3,2].

    Note: Recursive solution is trivial, could you do it iteratively?

    求二叉树的中序遍历,要求不是用递归。

    先用递归做一下,很简单。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        List result = new ArrayList<Integer>();
        public List<Integer> inorderTraversal(TreeNode root) {
            if( root == null)
                return result;
            getResult(root);
            return result;        
        }
    
        public void getResult(TreeNode root){
            if( root.left != null)
                getResult(root.left);
            result.add(root.val);
            if( root.right != null)
                getResult(root.right);
        }
        
    }

     不用递归,用栈实现也是很简单的。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        List result = new ArrayList<Integer>();
        public List<Integer> inorderTraversal(TreeNode root) {
            if( root == null)
                return result;
            Stack stack = new Stack<TreeNode>();
            TreeNode node = root;
            while( true ){
                if( node.left == null){
                    result.add(node.val);
                    if( node.right == null ){
                        if( stack.isEmpty() )
                            break;
                        else
                            node = (TreeNode) stack.pop();
                    }else{
                        node = node.right;
                    }
                    
                }else{
                    TreeNode flag = node;
                    node = node.left;
                    flag.left = null;
                    stack.push(flag);
                    
                }
            }
    
    
            return result;        
        }
        
    }
  • 相关阅读:
    Atcoder Grand Contest 003 题解
    Atcoder Grand Contest 002 题解
    Atcoder Grand Contest 001 题解
    网络流24题
    AGC005D ~K Perm Counting
    loj6089 小Y的背包计数问题
    CF932E Team Work
    组合数学相关
    SPOJ REPEATS
    [SDOI2008]Sandy的卡片
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5981983.html
Copyright © 2011-2022 走看看