码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法

时间:2017-07-16 11:11:51      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:必须掌握   value   while   解题思路   nbsp   flow   tps   content   could   

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].

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

confused what "{1,#,2,3}" means?

 > read more on how binary tree is serialized on OJ.

思路:二叉树的中序遍历,是典型的递归算法。可是题目中建议非递归实现。所以还是有些思考的。

只是算是基础题。感觉是必须掌握的。

代码例如以下(递归实现):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<Integer> list = new ArrayList<Integer>();
    public List<Integer> inorderTraversal(TreeNode root) {
    	/**
    	 * 中序遍历,先左子树,再根,最后右子树
    	 */
        
        if(root == null)
            return list;
        if(root.left != null){
            inorderTraversal(root.left);
        }
        list.add(root.val);   
        if(root.right != null){
            inorderTraversal(root.right);
        }
        return list;
    }
}
非递归实现:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
    	/**
    	 * 非递归实现中序遍历
    	 * 中序遍历,先左子树,再根。最后右子树
    	 */
    	
    	List<Integer> list = new ArrayList<Integer>();
    	
    	if(root == null)
    		return list;
    	
    	TreeNode p = root;
    	Stack<TreeNode> st = new Stack<>();
    	
    	while(p != null || !st.isEmpty()){
    		if(p != null){
    			st.push(p);
    			p = p.left;
    		}else{
    			p = st.pop();
    			list.add(p.val);
    			p = p.right;
    		}
    	}
        return list;
    }
}



leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法

标签:必须掌握   value   while   解题思路   nbsp   flow   tps   content   could   

原文地址:http://www.cnblogs.com/cxchanpin/p/7189633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!