94. Binary Tree Inorder Traversal
发布时间:2020-12-14 05:15:47 所属栏目:大数据 来源:网络整理
导读:Given a binary tree,return the? inorder ?traversal of its nodes‘ values. Example: Input: [1,null,2,3] 1 2 / 3Output: [1,3,2] Follow up:?Recursive solution is trivial,could you do it iteratively? ? ? 非递归二叉树中序遍历 ? java: 1 /** 2 *
Given a binary tree,return the?inorder?traversal of its nodes‘ values. Example: Input: [1,null,2,3]
1
2
/
3
Output: [1,3,2]
Follow up:?Recursive solution is trivial,could you do it iteratively? ? ? 非递归二叉树中序遍历 ? java: 1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> inorderTraversal(TreeNode root) { 12 List<Integer> res = new ArrayList<>() ; 13 if (root == null) 14 return res ; 15 Stack<TreeNode> stack = new Stack<>() ; 16 TreeNode cur = root ; 17 while(cur != null || !stack.isEmpty()){ 18 while(cur != null){ 19 stack.push(cur) ; 20 cur = cur.left ; 21 } 22 TreeNode node = stack.pop() ; 23 res.add(node.val) ; 24 cur = node.right ; 25 } 26 return res ; 27 } 28 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |