Novice Learning Algorithm----binary tree (sequential traversal)

Source: Internet
Author: User

This algorithm is only used once in the stack once the stack can be,

 //first of all the nodes of the left node of the root node into the stack, until the leaf node, the most left leaf node into the stack, and then determine whether it has reached the leaf node, if it is the value of the node in the stack, then the node out of the stack, because he did not change the     PublicArraylist<integer>postordertraversal (TreeNode root) {//Write your code herestack<treenode> s =NewStack<treenode>(); ArrayList<Integer> Result =NewArraylist<integer>(); if(Root = =NULL)returnResult;          TreeNode cur; TreeNode Pre=NULL;      S.push (root); //for all nodes first into the stack           while(!S.empty ()) {cur= S.peek ();//the current operand is the top element of the stack              if((cur.left==NULL&&cur.right==NULL)|| (Pre! =NULL&& (pre==cur.left| | pre==cur.right)))  {                  //if the current operand is empty, or p has left child or right child, but the left child and right child have been visited, indicating that the node can be accessed, then this node is useless and can be out of the stackResult.add (Cur.val);                  S.pop (); Pre= cur;//keep the current node for a while, and leave it to determine whether to access his parent node. }Else {                  if(cur.right!=NULL) S.push (cur.right);//If the right node of the current node is not empty on the stack, only the right node into the stack before you can guarantee that the order of access is right,                  if(cur.left!=NULL) S.push (Cur.left);//If left child is not empty, left child last into the stack              }          }          returnResult; }

Novice Learning Algorithm----binary tree (sequential traversal)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.