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 do it iteratively?
Confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Idea: The middle sequence traversal of two fork tree is a typical recursive algorithm. But the problem is not recursive implementation, so there is some thinking.
But the basic problem, the feeling must be mastered.
The code is as follows (recursive implementation):
/** * 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) { /** * Middle sequence traversal, first left subtree, then root, last right subtree * /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; }}
Non-recursive implementations:
/** * 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) { /** * Non-recursive implementation of a sequential traversal * Middle sequence traversal, first left subtree, then root, last right subtree * /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; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 94.Binary Tree inorder traversal (binary tree sequence traversal) thinking and method of solving problems