lintcode-easy-Binary Tree Inorder Traversal
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Binary Tree Inorder Traversal相关的知识,希望对你有一定的参考价值。
Given a binary tree, return the inorder traversal of its nodes‘ values.
Example
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
Challenge
Can you do it without recursion?
两种做法:
1. 使用递归, 思路比较直接,不多说了
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); if(root == null) return result; helper(root, result); return result; } public void helper(TreeNode root, ArrayList<Integer> result){ if(root == null) return; else{ helper(root.left, result); result.add(root.val); helper(root.right, result); return; } } }
2. 不使用递归的方法,使用一个stack,维护一个reference p
当p非null时,将p入栈,p指向左子树
当p为null时,栈顶元素出栈,加入arraylist,p再指向右子树
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); if(root == null) return result; TreeNode p = root; Stack<TreeNode> stack = new Stack<TreeNode>(); while(p != null || !stack.isEmpty()){ if(p != null){ stack.push(p); p = p.left; } else{ p = stack.pop(); result.add(p.val); p = p.right; } } return result; } }
以上是关于lintcode-easy-Binary Tree Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-easy-Binary Tree Inorder Traversal