Leetcode 156:binary Tree Upside down

Source: Internet
Author: User

Binary Tree Upside DownTotal Accepted: 813 Total Submissions: 2515

Given a binary tree where all the right nodes is either leaf nodes with a sibling (a left node that shares the same paren T node) or empty, flip it upside down and turn it to a tree where the original right nodes turned to left leaf nodes. Return the new root.

For example:
Given a binary tree {1,2,3,4,5},
    1   /   2   3/4   5

Return the root of the binary tree [4,5,2,#,#,3,1] .

   4  /  5   2    /    3   1  

Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

Analysis

Understand the definition of this tree, the answer is self-evident.

Note

None

[CODE]

/** * Definition for Binary tree * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right; *
   
    treenode (int x) {val = x;} *} */public class Solution {public    TreeNode upsidedownbinarytree (TreeNode root) {        stack<treenode> stack = new stack<treenode> ();                if (root==null) return null;        while (root.left! = null) {Stack.push (root); root=root.left;}        Stack.push (root);        while (!stack.empty ()) {            TreeNode node = Stack.pop ();            if (!stack.empty ()) {                node.right = Stack.peek ();                Node.left = Stack.peek (). right;            } else {                node.left = null;                Node.right = null;            }        }        return root;    }}
   


Leetcode 156:binary Tree Upside down

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.